【问题标题】:Is that possible that typescript inference to direct inference value and drop the key打字稿推断是否有可能直接推断值并删除密钥
【发布时间】:2020-03-24 07:18:01
【问题描述】:
class A {
  state: B
}
class B {
  something: C
}
class C {
  a: string;
  b: boolean;
}

type MagicType = ...

const c: MagicType<A>

c.state.a = "123"
c.state.b = true;

正如例子中提到的那样,在不改变类结构的情况下,是否有可能拥有魔法类型来实现这一点?

忽略something 键,只导出class c 属性

谢谢!

【问题讨论】:

    标签: typescript class types inference


    【解决方案1】:

    有对应的映射类型。

    class Foo{
      constructor(public bar:string,public baz:number){}
    }
    
    
    
    type State<T> = {
      "state": { [P in keyof T]: T[P] };
    };
    
    var fooState: State<Foo> = {
      state : new Foo("bar",1)
    }
    
    console.log(fooState.state.bar);
    

    游乐场link

    另见mapped types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 2021-06-08
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2018-06-09
      • 1970-01-01
      相关资源
      最近更新 更多