【发布时间】:2019-01-24 03:52:34
【问题描述】:
使用 TypeScript,可以创建一个需要两个属性中的至少一个的类型。有(至少)两种方法可以解决这个问题:using union types 和 a somewhat complexer generic solution。这两种解决方案效果很好。当两个属性都没有指定时,我能够创建并获得所需的编译器错误。
但是,当使用 final 类型来指定 react 组件中的 props 时,编译器无法找到这两个“必需”属性。这是一个简化的示例:
interface Base {
text?: string;
}
interface WithId extends Base {
id: number;
}
interface WithToken extends Base {
token: string;
}
type Identifiable = WithId | WithToken | (WithId & WithToken);
//OK
const item: Identifiable = {
text: "some text"
id: 4
};
//OK
const item: Identifiable = {
token: "some token"
};
//Error
const item: Identifiable = {
text: "some text"
};
//OK
export class MyComponent extends React.Component<Identifiable, any> {
render() {
//Error (see below)
return <p>{this.props.id}</p>
}
}
尝试访问两个必需的道具之一时收到的错误(无论在类中的什么位置)看起来像这样:
Property 'id' does not exist on type '(Readonly<{children?: ReactNode;}> & Readonly<WithId>) | (Readonly<{children?: ReactNode;}> & Readonly<WithToken>) | (Readonly<{children?: ReactNode;}> & Readonly<WithId & WithToken>)'
Property 'id' does not exist on type '(Readonly<{children?: ReactNode;}> & Readonly<WithToken>'.
有没有办法解决这个问题并让编译器理解这些要求?
注意:使用 TypeScript 3.0.1、React 16.4.2,以及迄今为止可用的最新类型。
【问题讨论】:
标签: reactjs typescript