myFunc can take either string or number But since argument is defined as T gives error when a string is passed.
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');
}
Error
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'.
How to fix this?
See in: TS Playground