【问题标题】:Type 'T' is not assignable to type 'string'类型“T”不可分配给类型“字符串”
【发布时间】:2020-04-03 20:01:00
【问题描述】:

问题来了:我想做一个函数,获取参数并返回相同的类型。

我做了一个最简单的例子:

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

Test 类型函数的这个简单实现抛出错误“Type 'T' is not assignable to type 'string'”

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

【问题讨论】:

    标签: typescript typescript3.0


    【解决方案1】:

    感谢爆破丸的回答。 问题是我必须让模板自己解决,所以我只是在没有指定类型的情况下创建了函数,它也很好用。

    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;
    

    【讨论】:

      【解决方案2】:

      https://github.com/Microsoft/TypeScript/issues/30496 实际上有这个问题的答案:Test 是一个泛型类型。您的定义不符合泛型类型,因为无法将T 分配给string。您应该可以使用 test&lt;number&gt;(num) 并让它正常工作,但如果 arg 是一个字符串,那将是不兼容的。

      不过,您可以将类型设为泛型。这将允许您在声明函数类型时缩小类型。

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

      【讨论】:

        猜你喜欢
        • 2021-10-04
        • 2020-10-28
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多