44

In TypeScript, which one is right?

[string] vs string[]

public searchOption: [string] = ['date'];
public searchOption: string[] = ['date'];
1

4 Answers 4

43

The first is a tuple and the second is an array of strings.

You can do this with tuples:

let searchOption: [string, number] = ['date', 22];
Sign up to request clarification or add additional context in comments.

Comments

16

The second one is right. If you want, you can take a look here https://www.typescriptlang.org/docs/handbook/basic-types.html

1 Comment

I know that this post is 4 years old, but this answer is misleading. The first one is also right for ['date'], see typescriptlang.org/docs/handbook/2/objects.html#tuple-types
9

If all you're going to do is make an array of strings they both seem to behave the same. However the 2nd one is the one you should use.

The first one is so you can make Tuples, like this.

let searchOption: [string, number] = ['date', 1];

Comments

4

These may appear the same, but they're different. As has been mentioned by others, the first is a tuple, and the second is an array of strings.

If your array has multiple strings (eg. ['one', 'two', 'three']) then the second (string[] is correct)

If, like in your original post, you only have one string in the array, then the first ([string]) is correct.

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.