如何使用类通用来确定条件类型的类型?
下面是一个基本示例和TSplayground 链接.
如何在不使用as
或任何其他手动更正的情况下拨打this.b
和this.a
?
type X<T> = T extends true ? number : string;
export class A<UN extends boolean, I extends X<UN>> {
useNumber: UN;
constructor(useNumber: UN) {
this.useNumber = useNumber;
}
a(input: string): string {
return `${input}j`;
}
b(input: number): number {
return input * 2;
}
c(input: I): string {
// I expected `UN` generic type (`this.useNumber`) is used as a type guard below.
//. =. UN ? I : I
// = UN ? X<true> : X<false>
// = UN ? number : string
const result = this.useNumber ? this.b(input) : this.a(input);
return result.toString();
}
}