Home > OS >  Interface for string field in typescript
Interface for string field in typescript

Time:09-27

I have a function whichYogaDoYouPractice that accepts a parameter type. The value of type can be any one of hatha, kriya, bhakti, jnana. Currently, I have my function written as follows:

function whichYogaDoYouPractice(type:'hatha'|'kriya'|'bhakti'|'jnana'){
 ...
}

I have more such functions where I want to use the parameter type for the above-mentioned values. I don't wish to mention all 4 type's every time I declare a function. I want to create an interface so my function looks something like the below function:

function whichYogaDoYouPractice(type:YogaType){
 ...
}

I can create interface for objects like below:

export interface ObjectInterface{
 id:string;
 name:string;
}

But I want to create an interface only for a string that can only be of any of the 4 values I mention in the interface so that I can use it with one word YogaType for the above example. Is it possible in Typescript? If yes, how? Thank You!

CodePudding user response:

You can just create a union type:

type YogaType = 'hatha'|'kriya'|'bhakti'|'jnana'

function whichYogaDoYouPractice(type: YogaType){
}

Playground

Or create a enum:

enum Yoga {
  hatha,
  kriya,
  bhakti,
  jnana
}

function whichYogaDoYouPractice2(type: Yoga){
}
  • Related