[TypeScript] Array and Tuple

수민🐣·2022년 11월 9일
0

TypeScript

목록 보기
6/16

Array

두가지 표현 방법

const numbers: number[] = [1,2,3];

const numbers: Array<number> = [1,2,3]; // Generic
const fruits: string[] = ['🍓', '🥭'];
const num: number[] = [1, 3, 4];
const scroes: Array<number> = [1, 3, 4]; // Generic

function printArray(fruits: readonly string[]) {
  /* readonly : 주어진 데이터를 함수 내부에서 변경을 할 수 없도록
	fruits: readonly string[] ⭕
	fruits: readonly Array<string> ❌
 */
}

Tuple

서로 다른 타입을 함께 가질 수 있는 배열
length와, 각 element의 타입이 고정되어 있는 배열
하지만 좋은 느낌이 아니라 대체로 interface, type alias, class를 사용

let student: [string, number];
student = ['name', 123];
student[0] // name 💩
student[1] // 123 💩

const [name, age] = student; // 데이터 원본이 아니라 임의라서 💩
  • 예시
const [state, setState] = useState();
// two array
// [any, function]

0개의 댓글