简体   繁体   English

如何使用 Type 参数限制 Typescript 中的对象字段

[英]How to restrict object fields in Typescript using Type parameter

I am using Typescript.我正在使用打字稿。 I want to create an Object like this,我想创建一个这样的对象,

const statusMessageMap = {
  'ENABLE': 'This is enable',
  'DISABLE': 'This is disable',
}

And I want to restrict fields of this object.我想限制这个对象的字段。 I can easily do it like this...我可以很容易地做到这一点...

interface Status = {
  ENABLE: string;
  DISABLE: string;
}

const statusMessageMap: Status = {
  'ENABLE': 'This is enable',
  'DISABLE': 'This is disable',
}

But I already have a type defined before and I want to keep it.但是我之前已经定义了一个类型,我想保留它。

type OldStatus = 'ENABLED' | 'DISABLE'

But it is not working like this...但它不是这样工作的......

//this is not working
const statusMessageMap: OldStatus = {
  'ENABLE': 'This is enable',
  'DISABLE': 'This is disable',
} 

I don't want to keep both Status and OldStatus because, it will make me to update in two places if I want to add a new status.我不想同时保留状态状态,因为如果我想添加新状态,它会让我在两个地方更新。

I want to keep my OldStatus type and want to use it to restrict type of the object.我想保留我的OldStatus类型并想用它来限制对象的类型。 How can I do it?我该怎么做? Is it possible to create a new interface extending the OldStatus type?是否可以创建一个扩展OldStatus类型的新接口?

Your message map type should be { [key in OldStatus]: string } using OldStatus :您的消息映射类型应该是{ [key in OldStatus]: string }使用OldStatus

type OldStatus = 'ENABLE' | 'DISABLE'

const statusMessageMap: { [key in OldStatus]: string } = {
  'ENABLE': 'This is enable',
  'DISABLE': 'This is disable',
}

Playground 操场

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

相关问题 使用类型参数的TypeScript - TypeScript using type parameter 类型检查...... object 的 rest 字段与 Typescript - Type check … rest fields of an object with Typescript 如何推断 TypeScript 中的参数类型? - How to infer parameter type in TypeScript? 如何使用 Typescript 键入 ref 参数 - How to type a ref parameter with Typescript 如何使用打字稿定义具有不同字段的对象? - How can I define an object to have different fields using typescript? 如何使用类型保护验证 typescript 中 object 中的字段 - How to validate fields inside object in typescript using typeguards TypeScript:如何将返回类型作为参数的类型? - TypeScript: how to have return type be the type of a parameter? 如何解决 typescript 错误在“对象”类型上找不到带有“字符串”类型参数的索引签名 - How do i solve typescript error No index signature with a parameter of type 'string' was found on type 'Object' 打字稿错误:“对象”类型的参数无法分配给“ {} []”类型的参数 - Typescript error: Argument of type 'Object' is not assignable to parameter of type '{}[]' Typescript object:如何将键限制为特定字符串? - Typescript object: How do I restrict the keys to specific strings?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM