0

I am trying to create a method which parameter has fixed string value types but at the same time i want user to also provide value other than fixed string values.

function create(options: "A" | "B" ){

}


create("C");

Here when user is passing "C" value, typescript is throwing error. This can be fixed by casting "C" to any, but i don't want user to do anything but my method should take care of it.

Consider the options contains 100 of string values, so it is helping users to get those value in intillisense which will help users to don't remember it and use it.

enter image description here

Can i do anything from methods ?

2
  • 2
    Seems like what you want is function create(options: string) because when you say function should accept "A" and "B" and any other string value, you want any string value as the parameter type because that will include "A" and "B" as well. Commented Jun 22, 2021 at 5:27
  • May I ask what is the scenario you may need a logic like that? Commented Jun 22, 2021 at 6:27

1 Answer 1

1

I think it is better to overload your function:

function create(options: "A"): void
function create(options: "B"): void
function create(options: string): void
function create(options: string) { }


create()

IDE will be able to pick up allowed arguments along with string type: enter image description here

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.