TypeScript:在运行时访问类型信息
TypeScript: accessing type information at runtime
如果根据参数输入创建动态属性:
type ObjBuilder<Prop1 extends string, Prop2 extends string> = {
[P in Prop1 | Prop2]: P extends Prop2 ? ()=>boolean : ()=>string
}
function objectBuilder<Prop1 extends string, Prop2 extends string>(
prop1: string,
prop2: string,
) : ObjBuilder<Prop1, Prop2> {
return {
[prop1]: () => true,
[prop2]: () => prop2,
} as ObjBuilder<Prop1, Prop2>
}
// note the duplication of information in this code
const a = objectBuilder<'p1', 'p2'>('p1', 'p2')
console.log(a.p1()) // true
console.log(a.p2()) //'p2'
是否可以访问函数定义中的类型定义以避免 objectBuilder<'p1', 'p2'>('p1', 'p2')
的重复,而只有 objectBuilder<'p1', 'p2'>()
编译后的 javascript 可以访问字符串 p1
和 p2
?
换句话说,让 JavaScript 通过反射以某种方式访问类型信息并使其在运行时可用?
您可以推断参数的文字类型。
C考虑这个例子:
type ObjBuilder<Prop1 extends string, Prop2 extends string> = {
[P in Prop1 | Prop2]: P extends Prop2 ? () => boolean : () => string
}
function objectBuilder<Prop1 extends string, Prop2 extends string>(
prop1: Prop1,
prop2: Prop2,
): ObjBuilder<Prop1, Prop2> {
return {
[prop1]: () => true,
[prop2]: () => prop2,
} as ObjBuilder<Prop1, Prop2>
}
const a = objectBuilder('p1', 'p2')
console.log(a.p1())
console.log(a.p2())
您可能已经注意到,我使用 Prop1
和 Prop2
泛型作为参数类型而不是 string
。通过这种方式,TS 能够推断文字类型。
如果你对这个主题(函数参数类型推断)感兴趣,你可以查看我的 article
如果根据参数输入创建动态属性:
type ObjBuilder<Prop1 extends string, Prop2 extends string> = {
[P in Prop1 | Prop2]: P extends Prop2 ? ()=>boolean : ()=>string
}
function objectBuilder<Prop1 extends string, Prop2 extends string>(
prop1: string,
prop2: string,
) : ObjBuilder<Prop1, Prop2> {
return {
[prop1]: () => true,
[prop2]: () => prop2,
} as ObjBuilder<Prop1, Prop2>
}
// note the duplication of information in this code
const a = objectBuilder<'p1', 'p2'>('p1', 'p2')
console.log(a.p1()) // true
console.log(a.p2()) //'p2'
是否可以访问函数定义中的类型定义以避免 objectBuilder<'p1', 'p2'>('p1', 'p2')
的重复,而只有 objectBuilder<'p1', 'p2'>()
编译后的 javascript 可以访问字符串 p1
和 p2
?
换句话说,让 JavaScript 通过反射以某种方式访问类型信息并使其在运行时可用?
您可以推断参数的文字类型。
C考虑这个例子:
type ObjBuilder<Prop1 extends string, Prop2 extends string> = {
[P in Prop1 | Prop2]: P extends Prop2 ? () => boolean : () => string
}
function objectBuilder<Prop1 extends string, Prop2 extends string>(
prop1: Prop1,
prop2: Prop2,
): ObjBuilder<Prop1, Prop2> {
return {
[prop1]: () => true,
[prop2]: () => prop2,
} as ObjBuilder<Prop1, Prop2>
}
const a = objectBuilder('p1', 'p2')
console.log(a.p1())
console.log(a.p2())
您可能已经注意到,我使用 Prop1
和 Prop2
泛型作为参数类型而不是 string
。通过这种方式,TS 能够推断文字类型。
如果你对这个主题(函数参数类型推断)感兴趣,你可以查看我的 article