How to restrict object fields in Typescript using Type parameter

449 views Asked by At

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?

1

There are 1 answers

0
Psidom On BEST ANSWER

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