类型:特定接口的键数组

时间:2018-07-20 16:13:34

标签: typescript

我有一个界面:

interface ParentProps {
   one: number;
   two: string;
   three: string;
}

父React.Component,其道具由接口指定,并将['one','two','three']传递给Child。

   class Parent extends React.Component<ParentProps> {
...
   return (
       <Child keys={Object.keys(this.props)}>Hello</Child>
   )
...

这是儿童代码的摘录:

...
   return this.props.keys.map(v => <div>v</div>)
...

问题::如何指定this.props.keys应该为array of keys of ParentProps类型,在这种情况下为['one', 'two', 'three'],因此如果我添加第四个prop到ParentProps(即{四:数字}),它会自动显示在ChildProps上吗?

这是我尝试过的:

1)给出array.prototype的键:

interface ChildProps {
     keys: keyof ParentProps[];
}

2)给出了父项道具之一的数组:

interface ChildProps {
     keys: [keyof ParentProps];
}

3)给出以下信息:(“一个” |“两个” |“三个”)[]

interface ChildProps {
    keys: (keyof ParentProps)[];
}

1 个答案:

答案 0 :(得分:0)

看起来,打字稿无法识别this.props的键,该键由Object.keys包装,并推断我们以string[]的形式传递给子级的值的类型。这样传递道具可以解决问题:

class Parent extends React.Component<ParentProps> {
...
   return (
       <Child keys={Object.keys(this.props) as (keys ParentProps)[]}>Hello</Child>
   )
...
相关问题