javascript - 在 react/typescript 中处理 prop 函数参数的最佳方式是什么?
说我有这个
type Props = {
onClose: () => void
}
const MyComponent = ({ onClose }: Props) => {
// my component
}
但是理论上 onClose 可以接受任何函数。可能还有一个参数。
所以我可以这样做:onClose: (arg) => void,但是如果有时这个类型是string,有时是number等等,会怎么样呢
我能想到的唯一方法是使用泛型,但这会变得相当混乱,我必须做类似这样的事情:
type Props<T> = {
onClose: (arg: T) => void
}
const MyComponent<T> = ({ onClose }: Props<T>) => {
// my component
}
如果我有很多函数,那将会有很多泛型。有更好/更干净的方式来处理这个问题吗?(我显然也不想使用 any)
答案#1
如果它可以是任何类型,那么类型就是 any。只需将参数设为可选。同时,使用类型定义 FC,而不是在 props 上设置类型。这样做在使用组件时可以获得类型推断。
type Props = {
onClose: (arg?: any) => void
}
const MyComponent: React.FC<Props> = ({ onClose }) => {
// my component
}
答案#2
你可以用以下内容替换 Props 定义。
type ComponentAllowedPropsKind = unknown
type Props<T> = Record<string,ComponentAllowedPropsKind>
const MyComponent<T> = ({ onClose }: Props<T>) => {
// my component
}
你可以比 unknown 更严格地限制属性的种类。你可以比 string 更严格地限制属性的名称。这个代码设计会迫使你在组件内部处理 类型保护,如果你想使用这些属性的话。
