【发布时间】:2021-06-28 11:47:21
【问题描述】:
我想创建一个对象 + getter 函数,如果我们不知道键是否在对象中,它将返回已知值类型(如果键 extends keyof typeof obj)或值类型不是。有点像这样:
const obj = {
a: 1,
b: 2,
c: 3
}
const a = obj.a
// typeof a = number
const b = obj['b']
// typeof b = number
let key: string = 'anything'
const d = obj[key]
// typeof d = number | undefined
if (d) {
// typeof d = number
} else {
// typeof d = undefined
}
在现实中发生的事情是
let key: string = 'anything'
const d = obj[key]
// TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; b: number; c: number; }'. No index signature with a parameter of type 'string' was found on type '{ a: number; b: number; c: number; }'.
I've been trying to create a `get` function which would work this way, but can't get it to work. The result type is always either `any` or `unknown`.
【问题讨论】:
-
我们怎么会不知道key是否存在于一个常量对象中呢?
标签: javascript typescript typescript-typings type-safety typescript-types