3

I've come across this type:

let a: [number | string];

I've googled and looked at the Typescript docs but I don't see this syntax mentioned. What is it, I see the base is a union of string or number but it's not a tuple nor is it an array. What does it correspond to? Can anyone explain in simple terms and how to initialise it and add values please.

2
  • Possible duplicate of What does the pipe(|) mean in typescript? Commented Feb 9, 2018 at 20:50
  • 1
    Looks like a tuple of only one item, where that item is either a string or a number. Valid values might be: [1] or ["somestring"] Commented Feb 9, 2018 at 20:50

2 Answers 2

4

It is a tuple of size 1. Contains either a number or a string

Sign up to request clarification or add additional context in comments.

1 Comment

I think the API doc for the valeu is confusing me as it says it is [string|number] - and so I init'd it by <[string]>[]; but it only accepts values and works as described if I pass it a string[]. Anyway I think you are correct it is simply just an 'odd' single element tuple.
3

Personally, I would describe this as an array that can only hold a single item, which has to be either a number or a string.

You can also describe the array as a tuple, but personally I feel that the entire point of tuples is that they should hold multiple values, rather than just one. Both are correct.

Sidenote: When I run into an unfamiliar syntax, I like to try them out in the typescript sandbox and look at the generated javascript code: https://www.typescriptlang.org/play/

2 Comments

I tried that website but it just converts it as var a. Still useful to use in future thank you.
Sorry, you're right that in this case the generated javascript code isn't very useful. I meant it more as a way of experimentation. For example, this will give you some insight in what's possible and isn't, without needing a development environment.

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.