【问题标题】:The type could be instantiated with a different subtype of constraint error可以使用不同的约束错误子类型来实例化该类型
【发布时间】:2021-11-24 14:38:51
【问题描述】:

我为每个函数写了三个相同类型的函数,让我们看看。

const func: <T extends string, K extends number = any>(arg: T) => K = () => {
  return 1;
};

const anotherFunc = <T extends string, K extends number = any>(arg: T): K => {
  return 1;
};

function someFunc<T extends string, K extends number = any>(arg: T): K {
  return 1;
}

如您所见,我将K 定义为所有数字中的数字,以在每个数字中返回一个数字,但出现了一个奇怪的错误:

这是第一个函数:

Type '() => 1' is not assignable to type '<T extends string, K extends number = any>(arg: T) => K'.
  Type 'number' is not assignable to type 'K'.
    'number' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint 'number'.

这是最后两个函数:

Type 'number' is not assignable to type 'K'.
  'number' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint 'number'

我认为这两个错误具有相同的意义。为什么 typescript 不能实现那种类型?

感谢您的帮助。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    几个观察结果。

    • 如果你从不使用args:T,为什么还要使用它?
    • 你为什么要扩展一个原语string and number 并将任何类型分配给K
    • 您的第一个function 是错误的。让转换器转换为经典功能
    const func: <T extends string, K extends number = any> function (args:T) {
      return K = function () { 
    return 1;
    }
    }
    

    你看到这两个错误了吗?

    • 我们使用 = 来分配值,您在 func 中没有使用它,例如查看 anotherFunc
    • 您忘记添加第三个错误是
    Declaration or statement expected.
    

    【讨论】:

    • K = function
    【解决方案2】:

    我不确定这是否重复,但请看看这个answer

    这是第一个例子的简化版:

    const func: <K extends number>() => K = () => {
        return 1;
    };
    

    现在,尝试调用这个函数:const result = func&lt;42&gt;(); // 42。 TS 假设,返回类型/值是42,但在运行时是1

    此外,42 &amp; { WAAAT: () =&gt; '?????' } 是数字的有效子类型。

    const result = func<42 & { WAAAT: () => '?????' }>();
    result.WAAAT() // ?????
    

    以上代码在 TypeScript 中编译,但在运行时抛出运行时错误。 请查看错误信息:

    K 可以使用不同的约束子类型 number 进行实例化

    42 &amp; { WAAAT: () =&gt; '?????' } 是约束number 的有效子类型。

    因此,不要将extends 视为equal 运算符。

    更多示例请查看我的article

    【讨论】:

    猜你喜欢
    • 2020-01-22
    • 2020-03-27
    • 2020-11-25
    • 2021-08-14
    • 2021-06-26
    • 2021-02-13
    • 2019-12-13
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多