【问题标题】:Extending indexable types Typescript [duplicate]扩展可索引类型 Typescript [重复]
【发布时间】:2021-11-20 14:48:06
【问题描述】:

我有表单验证接口

export interface SearchBarValidatorObj {
  [k: string]: KeyObjectValidator;
}

有没有办法给它添加“静态”类型?拥有这个功能

export interface SearchBarValidatorObj {
  required: string | boolean
  [k: string]: KeyObjectValidator;
}

这是 KeyObjectValidator 接口

interface KeyObjectValidator {
  value: string | number | RegExp;
  message?: string;
}

干杯!

【问题讨论】:

  • TypeScript 中没有与您要执行的操作相对应的特定类型。有各种解决方法。有关更多信息,请参阅the answer 这个重复的问题。如果我将那里的代码翻译成您的示例代码,它会生成this。祝你好运!

标签: javascript typescript typescript-generics


【解决方案1】:

是的,您可以使用交叉类型:

export interface SearchBarValidatorObj {
  [k: string]: KeyObjectValidator;
}

interface KeyObjectValidator {
  value: string | number | RegExp;
  message?: string;
}

type WithStatic = SearchBarValidatorObj & { required: string | boolean };

let obj!: WithStatic;
// these are valid
obj.required = false;
obj.a = { value: 5 };

// these are invalid
obj.required = 4;
obj.required = { value: 5 };

【讨论】:

  • 像这样的交叉点类型是缺少“默认”或“剩余”索引签名的解决方法之一。它们不容易初始化,因为编译器会尝试检查任何初始值的 required 属性是否与索引签名匹配,但它不会。在您的回答中,您避免通过编写 let obj!: WithStatic 进行初始化(这基本上保证了运行时错误......我想您可以改为编写 let obj = {} as WithStatic)但是没有类型安全的方法可以做到这一点。更多解释请参见this answer
  • 完全同意。只是想为所述问题提供可能的解决方案。
猜你喜欢
  • 1970-01-01
  • 2017-05-14
  • 2021-01-18
  • 2022-12-03
  • 2020-09-12
  • 2020-10-08
  • 2018-01-03
  • 1970-01-01
相关资源
最近更新 更多