【发布时间】:2020-12-09 07:38:41
【问题描述】:
我有任何普通 JS 对象的类型:
type Entity = {
[k: string]: any,
};
我正在逐步将 TS 添加到我的代码库中,因此我允许隐式任何。有了这种类型,我可以做到:
const user: Entity = ...;
user.name.includes(...);
但是,如果我想将它定义为任何没有对象或数组值的普通 JS 对象:
type Entity = {
[k: string]: string | number | boolean | null,
};
我得到:Property 'includes' does not exist on type 'string | number | boolean'.
这个我也试过了,不知道是不是有效的TS:
type Entity = {
[k: string]: Entity[k] extends Object ? never : Entity[k];,
};
但同样的事情:Property 'includes' does not exist on type 'never'.
在这种情况下是否可以让 TS 不抛出错误?我希望它表现得好像对象值的类型是any。
【问题讨论】:
-
如果你想让它表现得好像值类型是
any,你只需将any分配给值类型。否则你怎么看?我的意思是,如果您无论如何都要使用它们,那么将string | number | whatever分配给值有什么意义。 -
我尝试的时间比我愿意承认的要长,但我认为如果不使用 typeguard 之类的东西或增加一些开销是不可能的。还有其他人提出的东西几乎有效,但在这里不适用。
-
需要将 tsconfig.json 设置为
--lib dom,es2017Leo 请检查下面的这些链接,可能会有所帮助 stackoverflow.com/questions/40545329/… AND github.com/PatrickJS/angular-starter/issues/…
标签: javascript typescript