打字推断可能会引导推断值并放下键

问题描述 投票:0回答:1
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个回答
0
投票

有对应的映射类型。

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

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