typescript 如何修复“但”T“可以用约束的其他子类型示例化,”

sy5wg1nm  于 2023-02-05  发布在  TypeScript
关注(0)|答案(2)|浏览(140)

myFunc可以采用stringnumber,但由于参数定义为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');

}

错误

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'.

如何解决这个问题?
查看:TSPlayground

jjhzyzn0

jjhzyzn01#

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');
}

另一种方式:

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 {};
}
mftmpeh8

mftmpeh82#

如果它适合您的情况,您可以使类型约束更严格一些:

export const myComponent = <T extends Props<string | number>>(props: T) => {

  const {
    items = [],
    onValueChange
  } = props;

  const myFunc = (item: string | number) => {
    //do something
    console.log(item);
    onValueChange([item])
  }

  items.map(item => myFunc(item));

  myFunc('test');
}

playground link

相关问题