简体   繁体   中英

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. How can I do it? Is it possible to create a new interface extending the OldStatus type?

Your message map type should be { [key in OldStatus]: string } using OldStatus :

type OldStatus = 'ENABLE' | 'DISABLE'

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

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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