简体   繁体   English

Typescript:将类型定义为“任何类型除外”而不触发错误?

[英]Typescript: define a type as "any except type" without triggering errors?

I have a type for any plain JS object:我有一个适用于任何普通 JS object 的类型:

type Entity = {
  [k: string]: any,
};

I'm incrementally adding TS to my codebase, so I'm allowing implicit any.我逐渐将 TS 添加到我的代码库中,因此我允许隐式任何。 With this type, I can do:使用这种类型,我可以这样做:

const user: Entity = ...;
user.name.includes(...);

However, if I want to define it as any plain JS object without object or array values:但是,如果我想将它定义为任何没有 object 或数组值的普通 JS object:

type Entity = {
  [k: string]: string | number | boolean | null,
};

I get: Property 'includes' does not exist on type 'string | number | boolean'.我得到: Property 'includes' does not exist on type 'string | number | boolean'. Property 'includes' does not exist on type 'string | number | boolean'.

I also tried this, not sure if it's valid TS:我也试过这个,不确定它是否有效 TS:

type Entity = {
  [k: string]: Entity[k] extends Object ? never : Entity[k];,
};

But same thing: Property 'includes' does not exist on type 'never'.但同样的事情: Property 'includes' does not exist on type 'never'.

Is it possible to get TS to not throw errors in this case?在这种情况下是否可以让 TS 不抛出错误? I want it to behave as if the object value's type was any .我希望它表现得好像 object 值的类型是any

Unless someone comes up with a really clever way of working around Object and any and before not object works, I'd recommend trying to build something like除非有人想出一个非常聪明的方法来解决Object和之前的any not object工作,我建议尝试构建类似

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

Hopefully, you can narrow down your types.希望您可以缩小您的类型。 In the meantime, I'd try to add more precision and safety where possible.与此同时,我会尽可能地提高精确度和安全性。 If Entity comes from an external source, then you might want to consider using unknown type.如果Entity来自外部来源,那么您可能要考虑使用unknown类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM