简体   繁体   English

将 typescript 泛型与类成员类型一起使用

[英]Use typescript generic with class member type

interface MyState {
  balances: { [address: string]: BN };
}

const [ state, setState ] = useState</* what should I do? */>({});

I want to pass type of MyState.balances to useState's generic type like useState<typeof MyState.balances>({}) , but it didn't work.我想将 MyState.balances 的类型传递给 useState 的泛型类型,例如useState<typeof MyState.balances>({}) ,但它没有用。

How can I do that?我怎样才能做到这一点?

You can use an indexed access type :您可以使用索引访问类型

interface MyState {
  balances: { [address: string]: BN };
}

const [ state, setState ] = useState<MyState['balances']>({});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM