我试图在另一种类型中获得属性的类型。
例如,我有一个类型A
,我需要得到b
的类型。
我能想到的唯一方法是创建一个A
的实例,得到b
的类型。
type A = {
a: string
b: number
}
const a: A = null
type B = typeof a.b
您可以使用typeof
type A = {
a: string
b: number
}
const a: A = null
type B = typeof a.b
https://www.typescriptlang.org/docs/handbook/2/typeof-types.html
使用索引访问类型。将typescript示例调整为上面的示例:
type A = {
a: string
b: number
}
type B = A["b"];
不再需要创建实例,这使得它更可取。从https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html.