What is the difference between String [] and [String] in typescript?

What is the difference between String [] and [String] in typescript? What is the best option to choose between?

+4
source share
2 answers

They are not the same!

  • string[] says that the variable is an array with values ​​of type string (it can be of any size, even empty).
  • [string] says the variable is an array of size> = 1, and the first record is a string
  • the syntax [type]can be extended, for example [type1,type2,type3,typeN], and then requires the array to be at least N in size and the first N types to be as specified, while the following types are a union of these types.

Some examples illustrating this problem:

const testA:string[] = []; // good
const testB:[string] = []; // Error, array must have a string at position 0
const testC:[string, number] = ['a', 0]; // good
const testC1 = testC[0]; // testC1 is detected to be string
const testC2 = testC[1]; // testC2 is detected to be number

const testD:[string, number] = ['a', 0, '1']; //good
const testD1 = testD[2]; // testD1 is detected to be string | number
const testE:[string, number] = ['a', 0, 1]; //good
const testE1 = testE[2]; // testE1 is detected to be string | number
const testF:[string, number] = ['a', 0, null]; // Error, null is not of type string|number
+5
source

, TypeScript? TypeScript JavaScript, javascript

Javascript ,

// its OK to write code like 
let str = 'sfafsa' ;
str = true ; 

TypeScript , , , differnet

? TypeScript

let str: String[] = ['ge', 'gege', 'egeg'];
let str2: [String] = ['ge', 'gege', 'egeg'];

var str = ['ge', 'gege', 'egeg'];
var str2 = ['ge', 'gege', 'egeg'];

, , , BTW: - let str: String[]=[];

. - [String], , , String → ,

@Lusito , .

0

Source: https://habr.com/ru/post/1691362/


All Articles