类型 'T' 不可分配给类型 'string'

Type 'T' is not assignable to type 'string'

问题出在这里:我想创建一个获取参数并且 returns 相同类型的函数。

我做了最简单的例子:

type Test = <T>(arg: T) => T;
const test: Test = (arg: string) => arg;

测试类型函数的这种简单实现抛出错误"Type 'T' is not assignable to type 'string'"

有人能解释一下为什么在不使用模板参数中的 props 时会发生此错误事件吗?

https://github.com/Microsoft/TypeScript/issues/30496其实对此有答案:Test是泛型。您的定义不符合泛型类型,因为 T 无法分配给 string。您应该能够使用 test<number>(num) 并使其正常工作,但如果 arg 是一个字符串,那将是不兼容的。

不过,您可以使类型通用。这将允许您在声明函数类型时缩小类型。

type Test<T> = (arg: T) => T;
const test<string> = arg => arg; //arg is a string;

谢谢爆丸的解答。 问题是我必须让模板自行解析,所以我只是在没有指定类型的情况下创建了函数,它也运行良好。

type Test = <T>(arg: T) => T;
const test: Test = (arg) => arg;

这里是我正在处理的原始功能:

type VariableReducer = <T>(
  array: { label: string; value: T }[],
  variable: Readonly<IVariableDescriptor> | undefined,
  key: string,
) => { label: string; value: T }[];

const defaultVariableReducer: VariableReducer = (a, v) =>
  (v !== undefined && v.name !== undefined
    ? [...a, { label: editorLabel(v), value: v.name }]
    : a) as typeof a;