TypeScript
TIL | Array, readonly, Tuple
by J-Ymini
2021. 10. 23.
Array, readonly, Tuple,
Array
const fruits: string[] = ["1", "2"];
const fruits: number[] = [1, 2];
const fruits: Array<string> = ["1", "2"]; // 제네릭 챕터에서 다시 다룰 예정
const fruits: Array<number> = [1, 2];
- 배열의
element 타입을 위와 같이 지정할 수 있다.
readonly
const numbers: number[] = [1, 2];
const printArray1 = function (scores: readonly number[]) {
numbers.push(); // Property 'push' does not exist on type 'readonly number[]
};
const printArray2 = function (scores: readonly Array<number>) {
//'readonly' type modifier is only permitted on array and tuple literal types.
};
- 속성명 그대로 전달된 인자, 혹은 데이터가 수정되지 않도록 타입으로 보장하는 방법이다.
- object의 불변성을 보장하는 것이 중요하며
readonly 타입 지정은 Array<type> 방식과 같은 제네릭 표기법에 적용되지 않으므로 type[] 표기법으로 타입을 지정하는 것이 좋다.
Tuple
const tuple: [number, boolean] = [1, true];
tuple[0]; // 1;
tuple[3]; // Tuple type '[number, boolean]' of length '2' has no element at index '3'
const [id, hasjob] = tuple;
console.log(id, hasjob); // 1, true
Reference