gpt4 book ai didi

在 switch 语句、功能请求中进行 Typescript 类型检查,还是我做错了?

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:20 24 4
gpt4 key购买 nike

为什么 typescript 不知道 f1 在传递“SpecificStringObj”类型的参数时返回字符串?

interface F {
(s: AnyStringObj | SpecificStringObj): string | number;
}

interface AnyStringObj {
text: string;
}

interface SpecificStringObj {
text: "specificity";
}

const f1: F = s => {
switch (s.text) {
case "specificity":
return "s";
default:
return 1;
}
};

const stringObj: SpecificStringObj = {
text: "specificity"
};

const newStringObj: AnyStringObj = { text: f1(stringObj) };

此 Typescript 代码在对象的最后一行 .text 上失败,错误信息为:

[ts]
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'. [2322]
t.tsx(6, 3): The expected type comes from property 'text' which is declared here on type 'AnyStringObj'
(property) AnyStringObj.text: string

我可以解决这个问题:

const newStringObj: AnyStringObj = { text: f1(stringObj) as string };

我的问题是:为什么 typescript 不知道因为我传递了一个“SpecificStringObj”函数将返回字符串?


附加问题:这是否适合功能请求?

最佳答案

您正在寻找function overloading .

interface AnyStringObj {
text: string;
}

interface SpecificStringObj {
text: "specificity";
}

function f1(s: SpecificStringObj): string;
function f1(s: AnyStringObj): number;
function f1(s: AnyStringObj | SpecificStringObj): string | number {
switch (s.text) {
case "specificity":
return "s";
default:
return 1;
}
}


const stringObj: SpecificStringObj = {
text: "specificity"
};

const newStringObj: AnyStringObj = { text: f1(stringObj) };

Live example

关于在 switch 语句、功能请求中进行 Typescript 类型检查,还是我做错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54786677/

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