我有一個這樣的組件
type inputProps = {
value: string | number | boolean
onChange: (arg: string | number | boolean) => void
}
const Input = ({value, onChange}: inputProps) => {
return <div />
}
const OtherComponent = () => {
const [value, setValue] = React.useState(5)
// onChange type not compatible
return <Input value={value} onChange={setValue} />
}
const AnotherComponent = () => {
const [value, setValue] = React.useState('Hey')
// onChange type not compatible
return <Input value={value} onChange={setValue} />
}
游樂場鏈接
是否可以使arg
函式onChange
的值取決于值?
uj5u.com熱心網友回復:
是的。可以使用泛型:
type inputProps<T> = {
value: T;
onChange: (arg: T) => void;
};
const Input = <T,>({ value, onChange }: inputProps<T>) => {
return <div />;
};
uj5u.com熱心網友回復:
您可以首先將其定義InputProps
為泛型。
type InputProps<T extends string | number | boolean> = {
value: T;
onChange: (arg: T) => void;
};
然后你可以對不同的型別使用型別聯合。
const Input = ({
value,
onChange,
}: InputProps<string> | InputProps<number> | InputProps<boolean>) => {
return <div />;
};
const OtherComponent = () => {
const [value, setValue] = React.useState(5);
return <Input value={value} onChange={setValue} />;
};
const AnotherComponent = () => {
const [value, setValue] = React.useState('Hey');
return <Input value={value} onChange={setValue} />;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516215.html
標籤:打字稿
上一篇:如何獲取插槽或插槽元素作為參考?