gpt4 book ai didi

typescript - 为什么 'null' 或 'undefined' "is assignable"到 'string' 类型的参数?

转载 作者:行者123 更新时间:2023-12-03 19:04:23 25 4
gpt4 key购买 nike

让我们来 the following code in TypeScript :

function f<T>(a: T, b: T) { }

f("a", 1);
TypeScript 预计会失败:

Argument of type 'number' is not assignable to parameter of type 'string'.


然而, when I pass null (or undefined ) instead of 1 , TypeScript 改变泛型参数的类型 <T>string | null并且不会失败。
我有两个问题:
  • 为什么nullundefined被区别对待,例如number ?
  • 以及如何防止扩大(将类型更改为 string | null )?
  • 最佳答案

    Why null or undefined is treated differently than e.g. number?


    老实说,我不是 100% 确定为什么。正如评论中提到的,它推断 a是 'string' 类型,但允许 `null |不明确的。我做了一些实验,但我不明白为什么要这样做。

    And how to prevent the widening (changing type to string | null)?Some examples of what you can do:


    // Original
    function f<T>(a: T, b: T) { }

    f('a', 'b') // Allowed
    f(1, 2) // Allowed
    f(true, false) // Allowed
    f("a", 1); // Has error
    f("a", undefined); // Allowed
    f("a", null); // Allowed
    f(null, null) // Allowed

    // Extending then defining
    // Will only allow strings
    function g<T extends string = string>(a: T, b: T) { }

    g('a', 'b') // Allowed
    g(1, 2) // Has error
    g(true, false) // Has error
    g("a", 1); // Has error
    g("a", undefined); // Has error
    g("a", null); // Has error
    g(null, null) // Has error

    // Using Required
    // Does not allow null or undefined but allows other non strings
    function x<T>(a: Required<T>, b: Required<T>) { }

    x('a', 'b') // Allowed
    x(1, 2) // Allowed
    x(true, false) // Allowed
    x("a", 1); // Has error
    x("a", undefined); // Has error
    x("a", null); // Has error
    x(null, null) // Has error

    https://www.typescriptlang.org/play?ts=4.0.2#code/PTAEHkCcEsHNoHYEMA2AoAZgVwQYwC7QD2CoGAPACoB8AFEgFyiUA0oARk5QJSgDeoAL5pMtAORIxbMezG9QIUAEEUKIgHcApgBNRARjYAmXopVqtujLXyQsmthlQBnTSbBmNO0QCIk3tnrcANwKYAASSE6gmpCQRJA+fmw42poYiDrBocqqnpa0vv6gCFiqWaa5FqIlqmw1KG455l5oigCiAB74mgjaiLCg+AAWPaCp6Qj9rWAA6tCqoCQoAJ6gqOagTjb9Tpg4BMSksFTRXT3aUVswCAMAvJvbN3SMzGyczLwCwmiw4pLSsnkFWaul+BlAxmyESiMTiCV+NjsDmcrihkWisXiPwKSVAgRCimhGLh2MKyV6aQy2nK4XRsKxvzJxVKDQJtJhmPhtHqdRZjSJ9IS01AAFUnP1QAAlTQARyw0EgXkUABEiJooggiPg1pVmQt4qAUpSEDoOFhtesNFEtSNIMUSA9rrBdtg8IQHR0qM8mNK5QqdF63j7ZfLFdovZ8hCIOn8pKAZHJsh4qjHwZDgXk0DHEfYyCjGsmvDGmfi0RyScXcUaJpk2aABZysziivUafW6Y2Yzy9Q0y8SsUA

    关于typescript - 为什么 'null' 或 'undefined' "is assignable"到 'string' 类型的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64044048/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com