gpt4 book ai didi

typescript 类型保护 : Using the in operator

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:13 25 4
gpt4 key购买 nike

我正在学习 TypeScript 并从 Official DOCS 练习类型保护

我正在使用 TypeScript 3.5.3 测试所提供的示例(或多或少):

function exec(strOrNum: string | number) {
if ("substring" in strOrNum) {
return strOrNum.substring(1);
}
return strOrNum.toExponential(2);
}

但是 VSCode 抛出以下错误:

The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)

我不明白,有什么想法吗?

最佳答案

The in operator returns true if the specified property is in the specified object or its prototype chain.

这意味着它对对象(或数组)而不是字符串进行操作。

如果你想添加一个类型保护来区分 stringnumber 你必须使用 typeof:

function exec(strOrNum: string | number) {
if (typeof strOrNum === "string") {
return strOrNum.substring(1);
}
return strOrNum.toExponential(2);
}

如果您有两个接口(interface)的联合,您将使用 in 运算符:

interface A {
a: string;
}

interface B {
b: number;
}


function test(arg: A | B): string {
if ('a' in arg) {
return arg.a;
}
return arg.b.toFixed(2);
}

关于 typescript 类型保护 : Using the in operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57594637/

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