React、typescript 和 prop-types:如何使用自己的类型?
React, typescript and prop-types: how to use own type?
我有一个字符串类型字面量,形式为 type MyType = 'str1' | 'str2' | 'str3'
,我希望我的道具之一只接受这种类型,但我不知道如何告诉 PropTypes。
我试过使用 propTypes.oneOf(['str1', 'str2', 'str3'])
但打字稿将其推断为普通字符串,我不想要这样。
因为这是使用 TypeScript 的类型检查,所以您不要尝试在 React 运行时级别(propTypes
)执行它,而是在 TypeScript 级别执行它。
您的组件应该在其道具类型中使用您的字符串文字类型:
type MyComponentProps = {
propName: MyType;
}
那么如果它是一个 class 组件:
class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
// ...
}
或者,如果您使用的是功能组件:
const MyComponent: React.FC<MyComponentProps> = ({propName}) => {
// ...
};
我有一个字符串类型字面量,形式为 type MyType = 'str1' | 'str2' | 'str3'
,我希望我的道具之一只接受这种类型,但我不知道如何告诉 PropTypes。
我试过使用 propTypes.oneOf(['str1', 'str2', 'str3'])
但打字稿将其推断为普通字符串,我不想要这样。
因为这是使用 TypeScript 的类型检查,所以您不要尝试在 React 运行时级别(propTypes
)执行它,而是在 TypeScript 级别执行它。
您的组件应该在其道具类型中使用您的字符串文字类型:
type MyComponentProps = {
propName: MyType;
}
那么如果它是一个 class 组件:
class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
// ...
}
或者,如果您使用的是功能组件:
const MyComponent: React.FC<MyComponentProps> = ({propName}) => {
// ...
};