例如,我有以下类型,我使用 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/