gpt4 book ai didi

typescript - 'string | undefined' 类型的参数不可分配给 '"类型的参数无标题” | null | 未定义'

转载 作者:行者123 更新时间:2023-12-04 11:31:21 26 4
gpt4 key购买 nike

我无法理解 TypeScript 的类型推断。我认为这应该是有效的,不需要我指定 T 的类型:

export const deflt = <T>(val: (T | undefined | null), defaultVal: T): T => {
if (val === undefined || val === null) {
return defaultVal;
}
return val;
}

function maybeLabelName(name: string | undefined) {
return deflt(name, 'untitled');
}

对 deflt 的调用失败并出现以下错误:
Argument of type 'string | undefined' is not assignable to parameter of type '"untitled" | null | undefined'.
Type 'string' is not assignable to type '"untitled" | null | undefined'. [2345]

我可以通过更改 deflt 来修复它拨打以下电话之一:
// Option 1:
return deflt<string>(name, 'untitled');

// Option 2:
const s: string = 'untitled';
return deflt(name, s);

不应该 typescript 推断 string自动打字?

最佳答案

我认为这有点像 typescript 推断的方式 T在这种情况下。因为您指定了常量 'untitled' ,编译器会推断 T作为字符串文字类型 'untitled' ,因为这是最简单的推断站点 T从。然后它将根据字符串文字类型检查另一个参数并找到 string不可分配给 'untitled' .一种解决方法是在推断 T 时降低第二个参数的优先级。通过添加与 {} 的额外交集:

export const deflt = <T>(val: (T | undefined | null), defaultVal: T & {} ): T => {
if (val === undefined || val === null) {
return defaultVal;
}
return val;
}

function maybeLabelName(name: string | undefined) {
return deflt(name, 'untitled'); // T is string now
}

另一种解决方案(如果您不能更改原始函数)是显式断言 untitledstring ,这基本上是您已经尝试过的。
function maybeLabelName(name: string | undefined) {
return deflt(name, 'untitled' as string); // T is string now
}

关于typescript - 'string | undefined' 类型的参数不可分配给 '"类型的参数无标题” | null | 未定义',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472130/

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