Jan*_*fer 4 types type-inference type-conversion typescript
首先,我的问题的一些上下文:我有一个项目,我通过 Socket.IO 接收一个对象,因此我没有关于它的类型信息。此外,它是一种相当复杂的类型,因此需要进行大量检查以确保接收到的数据良好。
问题是我需要访问由接收对象中的字符串指定的本地对象的属性。这适用于第一维,因为我可以将 any 类型的属性说明符转换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)
Run Code Online (Sandbox Code Playgroud)
这是 TypeScript(版本 3)的已知限制还是我在这里遗漏了什么?
如果您有联合,则只能访问公共属性。keyof将为您提供一种类型的可公开访问的密钥。
对于strUnionTyped哪个string和字符串文字类型之间的联合,'hi'结果类型将具有与字符串相同的属性,因为联合中的两种类型具有与字符串相同的键。
因为objUnionTyped并且complexUnionTyped联合没有公共键,所以结果将是never
因为manuallyComplexUnionTyped你得到了 的键string,因为你写的实际上(keyof string) | { name: string, innerObj: { name: string }}不是keyof (string | { name: string, innerObj: { name: string }})这样你得到的键string与你指定的对象类型结合在一起。
要获取联合的所有成员的键,您可以使用条件类型:
type AllUnionMemberKeys<T> = T extends any ? keyof T : never;
let objUnionTyped: AllUnionMemberKeys<typeof objUnion>;
let complexUnionTyped: AllUnionMemberKeys<typeof complexUnion>;
Run Code Online (Sandbox Code Playgroud)
编辑
条件类型帮助获取所有联合成员的键的原因是因为条件类型分布在裸类型参数上。所以在我们的例子中
AllUnionMemberKeys<typeof objUnion> = (keyof typeof obj) | (keyof string)
Run Code Online (Sandbox Code Playgroud)