gpt4 book ai didi

TypeScript 类型保护和 "only refers to a type, but is being used as a value here."

转载 作者:行者123 更新时间:2023-12-05 04:02:11 29 4
gpt4 key购买 nike

我正在使用 Typescript 3.2.2,无法实现类型保护的最基本实现:

interface Bird {
fly(): boolean;
}

interface Fish {
swim(): boolean;
}

function swimIfYouCan(x: Fish | Bird) {
if ((<Fish>x).swim) {
return true
}
}

这会产生 Error:(50, 11) TS2693: 'Fish' only referenced a type, but is being used as a value here. 在 WebStorm 和 SyntaxError:/Users/sea-kent/git/docket-management/webapp/src/App.tsx:来自 yarn 的意外 token (51:8)。启用此语法是否需要配置?

最佳答案

对于您的问题,我想到了三种不同的方法。

  1. 如果你想转换它并直接使用它,你必须使用 as 运算符(正如@jonrsharpe 在评论中提到的),例如 (x as鱼).游泳

  2. 使用 in 运算符检查它是否可用,例如if ('swim' in x)

  3. 最后但并非最不重要的一点(在我看来,这种情况是最好的情况),只需执行一个检查实例来检查您拥有的实例:if (x instance of Fish)

编辑:没有充分阅读问题,您无法在运行时检查接口(interface)。但是在接口(interface)之上创建一个类没有坏处

关于TypeScript 类型保护和 "only refers to a type, but is being used as a value here.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54634205/

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