首页 > 解决方案 > 如何修复“但 'T' 可以用不同的约束子类型实例化。”

问题描述

myFunc可以采用stringornumber但是由于参数被定义为 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'.

如何解决这个问题?

参见:TS 游乐场

标签: typescripttypescript-generics

解决方案


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

// For typing to work
declare namespace React {
  type FC<T> = (props: T) => {};
};

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

推荐阅读