티스토리 뷰

TIL

TIL 230405 string[]과 [string]

2021bong 2023. 4. 5. 23:12

놀라는 오랑우탄

여러분은 string[]과 [string]이 다른 것이라는 사실을 알고 계십니까...?

 

오늘 ChatGPT에게 물어보며 문제를 해결하던 중 새로운 개념을 발견했다.

 

[string] is a tuple type with a single element of type string,

while string[] is an array type that can have zero or more elements of type string.

const tuple: [string] = ["hello"]; // valid
const array: string[] = ["world"]; // valid

const anotherTuple: [string] = []; // error: expects exactly one element
const anotherArray: string[] = []; // valid: empty array

In general, tuples are used when you want to represent a fixed-length collection of values of different types, while arrays are used when you want to represent a variable-length collection of values of the same type.


[string]과 string[]은 다르다..!

[string]은 문자열을 1개만 가지는 고정된 타입이고, string[]은 문자열을 요소로 가지는 배열 타입이다.

[string]은 무조건 요소 1개를 가지고 있어야하고, string[]은 빈문자열도 가능하다.

// [string]
const strArr1 : [string] = ['hello'] // 문제 없음
const strArr2 : [string] = [] // 에러 : Type '[]' is not assignable to type '[string]'. Source has 0 element(s) but target requires 1.
// string[]
const stringArr1 : string[] = ['hello'] // 둘 다 문제 없음
const stringArr2 : string[] = []

 

여러개도 가능하다.

const twoStrArr1 : [string, string] = [] // Type '[]' is not assignable to type '[string, string]'. Source has 0 element(s) but target requires 2.
const twoStrArr2 : [string, string] = ['hello'] // Type '[string]' is not assignable to type '[string, string]'. Source has 1 element(s) but target requires 2.
const twoStrArr3 : [string, string] = ['hello', 'world'] // 문제 없음
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함