typescript - 如何在 Typescript 中输入 es6 对象/字典

标签 typescript ecmascript-6

例如,我有以下类型,我使用 es6 对象作为字典。

type User = {
    id: string,
    name: string   
}
const usersDict = { [key: string]: User  } = {}

但问题是,如果我尝试获取一个不存在的用户 ID,则上面的输入是不正确的。例如

const user = usersDict['user_id_that_doesnt_exist'] // type of user is User

我应该像下面这样输入 usersDict 吗?

const usersDict = { [key: string]: User | undefined } = {}

这一个的问题是在下面的例子中循环遍历值

const usersDict = { [key: string]: User | undefined } = {}
Object.values(usersDict).map((user)=>{
    // here the type of user is User|undefined, 
    // but it really should be just User type,
    // since it's impossible to be undefined
})

最佳答案

如果可以使用noUncheckedIndexAccess在你的 tsconfig 然后你会得到 all the behavior you want :

type User = {
  id: string,
  name: string
}

type UserDictionary = {
  [userId: string]: User
}

const usersDict: UserDictionary = {};

const user = usersDict['user_id_that_doesnt_exist'] // type of user is User | undefined

Object.values(usersDict).map((user)=>{
    // here the type of user is User, as desired
})

关于typescript - 如何在 Typescript 中输入 es6 对象/字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69171860/

相关文章:

reactjs - 与WebSocket react useState导致数组无法正确更新

web - 使用 Web Essentials 2013 生成 typescript 智能感知文件不起作用

javascript - 似乎无法执行传递给变量的函数

javascript - 从箭头函数内部访问方法变量

javascript - window.customElements.define() 和 document.registerElement() 有什么区别

javascript - ECMAScript 中的表达式语句实际上是什么

javascript - React Redux mapStateToProps 在第二次调用中加载数据

javascript - typescript :不可分配给类型错误

javascript - typescript : unable to read a property of an object even though it's there

javascript - Office-JS 可以触发 VBA 工作簿或工作表事件过程吗?