2

I'd like to use this array with a union type, but TS rightly assumes that its type is string: "Argument of type 'string' is not assignable to parameter of type '"a" | "b"'."

function doSomething(value: "a" | "b"){}

["a", "b"].map(e => doSomething(e));

Is there a ways in which I can define the types of the array elements? If not, is there another way to solve this problem? I do not want to cast it in map().

1
  • 1
    You could use a const assertion to tell the compiler to infer a more specific type for ["a", "b"], like this. Does that meet your needs or is there some issue with it? Commented May 31, 2022 at 17:02

2 Answers 2

1

The correct answer is using a const assertion:

function doSomething(value: "a" | "b"){}

(["a", "b"] as const).map(e => doSomething(e));
Sign up to request clarification or add additional context in comments.

Comments

0

If you define the union type and add a type assertion, you can limit the type of that array to only accept union members.

type AorB = 'a' | 'b';
const testArray: AorB[] = ['a', 'b'];

function doSomething(value: AorB) {...};


const test2: AorB[] = ['b', 'c'] // <- Errors because 'c' is not part of the union.

The type needs to be narrowed at some point from string to AorB: either when defining the array to only accept AorB, using a type guard to narrow properly from string to AorB, or the in the receiving function.

2 Comments

That's not the question. jcalz already answered it properly.
I'm simply providing an alternative solution because 1) there was no accepted answer and 2) you have yet to respond to what you said is the answer so we have no indication this is closed.

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.