Typescript:从类的另一个属性类型推断属性类型

问题描述 投票:0回答:0

我想从另一个类属性类型推断出一个类型。

  • if
    foo
    属性是字符串
    'x'
    bar 属性类型是接口
    X
  • if
    foo
    属性是字符串
    'y'
    bar 属性类型是接口
    Y
  • if
    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)
      }
}

游乐场

typescript
© www.soinside.com 2019 - 2024. All rights reserved.