Sus*_*ath 5 typescript typescript-generics
myFunc可以采用string或number但由于参数被定义为 T 在传递字符串时给出错误。
interface Props<T> {
items: T[],
onValueChange: (vals: T[]) => void;
}
export const myComponent = <T extends string | number>(props: Props<T>) => {
const {
items = [],
onValueChange
} = props;
const myFunc = (item: T) => {
//do something
console.log(item);
onValueChange([item])
}
items.map(item => myFunc(item));
myFunc('test');
}
Run Code Online (Sandbox Code Playgroud)
错误
Argument of type 'string' is not assignable to parameter of type 'T'.
'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
参见:TS 游乐场
编译器消息实际上非常清楚:您已将myComponent函数限制为仅接受具有已解析类型的 props,例如string、number、string|number或never。您还使用对该函数施加的相同约束来限制可以接收的类型myFunc(此时是传递给 的任何类型myComponent)。
编译器试图引起您注意的问题是,如果myComponent使用Props<number>,调用,则T仅限于number,这也是myFunc将被限制的内容,因此,如果您这样做,myFunc('test');您可能会违反当前的约束,myFunc即它只接受number类型,而不是string.
如果您不希望遵守此保障措施,您可以摆脱限制并允许两者在myFunc合同myComponent上相互独立,这样您就可以做您最初想做的事情:
interface Props<T> {
items: T[],
onValueChange: (vals: T[]) => void;
}
type ItemType = string | number;
export const myComponent = (props: Props<ItemType>) => {
const {
items = [],
onValueChange
} = props;
const myFunc = (item: ItemType) => {
//do something
console.log(item);
onValueChange([item])
}
items.map(item => myFunc(item));
myFunc('test');
}
Run Code Online (Sandbox Code Playgroud)
其他方式:
interface Props<T> {
items: T[],
onValueChange: (vals: T[]) => void;
}
export const myComponent: React.FC<Props<string | number>> = ({items = [], onValueChange}) => {
const myFunc = (item: string | number) => {
//do something
console.log(item);
onValueChange([item])
}
items.map(item => myFunc(item));
myFunc('test');
return {};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6316 次 |
| 最近记录: |