简体   繁体   English

Typescript 接口特定键不同于索引

[英]Typescript interface specific keys different than index

I have an object with nearly all strings, except a few keys (which are known) which are string[] .我有一个 object几乎所有字符串,除了几个键(已知)是string[]

Interface MostlyStrings{
   [key:string]:string,
   specificKey1:string[],
   specificKey2:string[],
}

This does not work because string[] does not match the index.这不起作用,因为string[]与索引不匹配。

I want to avoid [key:string]:string|string[] because then I will have to specify between string and array in all code.我想避免[key:string]:string|string[]因为那样我必须在所有代码中指定字符串和数组。

Is it possible to interface that everything except a few known keys is a string ?是否可以接口除了几个已知键之外的所有内容都是string

There's an open issue on the TS repo that's been tracking this for the past few years.过去几年一直在跟踪的 TS repo 上有一个未解决的问题。 Currently, it's not possible to do this.目前,无法做到这一点。

You can achieve a similar effect by using an intersection type:您可以通过使用交集类型来实现类似的效果:

type MostlyStrings = {
   [key: string]: string;
} & {
   specificKey1: string[];
   specificKey2: string[];
};

You won't be able to construct an object literal of this type, but it will at least type-check/autocomplete correctly.您将无法构造此类型的 object 文字,但它至少会正确地进行类型检查/自动完成。 In practice, you'll just need to do what you did in your example and update the index signature to include the types of the known properties as well, even though it doesn't accurately reflect your intention.在实践中,您只需要执行您在示例中所做的操作并更新索引签名以包含已知属性的类型,即使它不能准确反映您的意图。

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

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