0

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!

1 Answer 1

2

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){
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.