Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between string[] and [string]

Consider the following Typescript example. The first line results in an error 'type undefined[] is not assignable to type [string]'. The last two lines do compile.

let givesAnError: [string] = [];
let isOK: string[] = [];
let isAlsoOK: [string] = ["foo"];

How do you have to interprete the type definition [string] in Typescript?

like image 770
Gie Spaepen Avatar asked Sep 21 '16 10:09

Gie Spaepen


People also ask

What is difference between String [] and string?

String[] and String... are the same thing internally, i. e., an array of Strings. The difference is that when you use a varargs parameter ( String... ) you can call the method like: public void myMethod( String...

Is String [] the same as array string?

There's no difference between the two, it's the same.

What is the difference between string and string [] in C#?

string is an alias in the C# language for System. String . Both of them are compiled to System. String in IL (Intermediate Language), so there is no difference.

What is the difference between String [] args and String args?

(String… args) is an array of parameters of type String, whereas String[] is a single parameter. String[] can full fill the same purpose but just (String… args)provides more readability and easiness to use.


2 Answers

The first (givesAnError) and last (isAlsoOK) are tuples, and the second (isOK) is an array.

With arrays all of your elements are of the same type:

let a: string[];
let b: boolean[];
let c: any[];

But with tuples you can have different types (and a fixed length):

let a: [string, boolean, number];
let b: [any, any, string];

So:

a = ["str1", true, 4]; // fine
b = [true, 3, "str"]; // fine

But:

a = [4, true, 3]; // not fine as the first element is not a string
b = [true, 3]; // not fine because b has only two elements instead of 3

It's important to understand the the javascript output will always use arrays, as there's no such thing as tuple in js.
But for the compilation time it is useful.

like image 107
Nitzan Tomer Avatar answered Oct 07 '22 17:10

Nitzan Tomer


Straight to it

string[] // n-length array, must only contain strings

[string] // must be 1-length array, first element must be a string
like image 20
King Friday Avatar answered Oct 07 '22 18:10

King Friday