0

Can someone explain are those 2 array union types identical? And if they are not the same, what would be the correct use case for each one?

const a: string[] | number[] = [];
const b: (string|number)[] = []
3
  • Does this answer your question? object[] | object[] type lacks a call signature for 'find(),foreach()' Commented Nov 10, 2020 at 23:07
  • I assume you mean b: (string | number)[] because string|number[] means either a string as a plain value or an array of numbers. Commented Nov 10, 2020 at 23:08
  • Yes Vlaz, exactly I mean b: (string | number)[]. Will update the question now. Commented Nov 10, 2020 at 23:54

2 Answers 2

1

They are not identical. Here is the difference:

const a: string[] | number[] = [];

This means that a can be array of strings or array of numbers. So:

// Array of strings
a = ['h', 'e'];
// or Array of numbers 
a = [1, 2];

const a: string|number[] = []

Means that a is either a string OR an array of numbers

// string
a = 'hello';
// or array of numbers
a = [1, 2];

const a: (string|number)[] = []

Means that a is an array where each item in the array can be a number or a string so:

// (string | number) array
a = ['h', 1];
Sign up to request clarification or add additional context in comments.

Comments

1

b is a string or an array of number. Therefore these are not identical. b could be written as const b: (string | number)[] = [];. However, this allows mixed types like const b: (string | number)[] = [1, 'a'];, which a does not.

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.