首先,让我们来了解一下我的问题背景:我有一个项目,在该项目中,我通过Socket.IO接收一个对象,因此我没有关于它的类型信息。此外,它是一种相当复杂的类型,因此需要进行大量检查以确保接收到的数据是好的。
问题在于,我需要访问由接收到的对象中字符串指定的本地对象的属性。对于第一个维度,这可以正常工作,因为我可以将任何类型的属性说明符强制转换为要访问的
结果变量的类型显然是一个相当冗长的联合类型(将所有属性
通过之前的检查,我可以保证该属性存在,并且我99%确定代码在编译后会运行。只是编译器在抱怨。
下面是一些非常简单的代码,重现了这种行为以及观察到的和期望的类型。
问题在于,我需要访问由接收到的对象中字符串指定的本地对象的属性。对于第一个维度,这可以正常工作,因为我可以将任何类型的属性说明符强制转换为要访问的
keyof typeof
(例如:this.property[<keyof typeof this.property> data.property]
)。结果变量的类型显然是一个相当冗长的联合类型(将所有属性
this.property
的类型合并)。只要其中一个属性是非原始类型,keyof typeof subproperty
就会被推断为never
。通过之前的检查,我可以保证该属性存在,并且我99%确定代码在编译后会运行。只是编译器在抱怨。
下面是一些非常简单的代码,重现了这种行为以及观察到的和期望的类型。
const str = 'hi';
const obj = {};
const complexObj = {
name: 'complexObject',
innerObj: {
name: 'InnerObject',
},
};
let strUnion: typeof str | string; // type: string
let objUnion: typeof obj | string; // type: string | {}
let complexUnion: typeof complexObj | string; // type: string | { ... as expected ... }
let strTyped: keyof typeof str; // type: number | "toString" | "charAt" | ...
let objTyped: keyof typeof obj; // type: never (which makes sense as there are no keys)
let complexObjTyped: keyof typeof complexObj; // type: "name" | "innerObject"
let strUnionTyped: keyof typeof strUnion; // type: number | "toString" | ...
let objUnionTyped: keyof typeof objUnion; // type: never (expected: number | "toString" | ... (same as string))
let complexUnionTyped: keyof typeof complexUnion; // type: never (expected: "name" | "innerObject" | number | "toString" | ... and all the rest of the string properties ...)
let manuallyComplexUnionTyped: keyof string | { name: string, innerObj: { name: string }}; // type: number | "toString" | ... (works as expected)
这是 TypeScript(3 版本)的已知限制,还是我理解有误?
keyof typeof something
完全相同,不是吗? - Jan Hettenkofer