我想从另一个类属性类型推断出一个类型。
foo
属性是字符串 'x'
bar 属性类型是接口 X
foo
属性是字符串 'y'
bar 属性类型是接口 Y
foo
属性是字符串 'z'
bar 属性类型是接口 Z
这是我的方法
interface X { x: boolean }
interface Y { y: boolean }
interface Z { z: boolean }
type InferResult<T> = T extends 'x' ? X :
T extends 'y' ? Y :
T extends 'z' ? Z : Z; // default Z
class MyClass {
private foo: 'x' | 'y' | 'z' = "x";
private bar!: InferResult<MyClass["foo"]>; // expected X because foo is X but bar is X | Y | Z
constructor(foo: 'x' | 'y' | 'z'){
this.foo = foo;
}
setBar(value: boolean){
if( this.foo === 'x') {
this.bar = {x: value};
} else if( this.foo === 'y') {
this.bar = {y: value};
} else if( this.foo === 'z') {
this.bar = {z: value};
} else if( this.foo === 'z') {
this.bar = {y: value}; // this should be an error for ts!!!!
}
console.log(this.bar, this.foo)
}
}