【问题标题】:Typescript: define a type as "any except type" without triggering errors?打字稿:将类型定义为“除类型之外的任何类型”而不触发错误?
【发布时间】: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,es2017 Leo 请检查下面的这些链接,可能会有所帮助 stackoverflow.com/questions/40545329/… AND github.com/PatrickJS/angular-starter/issues/…

标签: javascript typescript


【解决方案1】:

除非有人想出一个非常聪明的方法来解决 Objectany 并且在 not object 工作之前,我建议尝试构建类似的东西

type Entity = {
  name?: string;
  [key: string]: string | boolean | number | undefined;
}
type Entity = {
  name?: string;
  [key: string]: any;
}

希望您可以缩小您的类型。与此同时,我会尽可能地增加精度和安全性。如果Entity 来自外部来源,那么您可能需要考虑使用unknown 类型。

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 2017-03-03
    • 2021-11-07
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2018-02-02
    相关资源
    最近更新 更多