타입의 종류
2022. 12. 23. 14:58ㆍ프로그래밍/TypeScript
- 목차
String (문자열)
const str: string = 'Hello';
Number (숫자)
const num: number = 2;
const pi: number = 3.14;
const infi: number = Infinity;
const nan: number = NaN;
Boolean (true, false)
const isDone: boolean = false;
Array (배열)
// 두 가지 방법
const fruits: string[] = ['Apple', 'Banana', 'Orange'];
const fruits: Array<string> = ['Apple', 'Banana', 'Orange'];
// 유니언 타입
const array: (string | number)[] = ['Apple', 1, 2];
const array: Array<string | number> = ['Apple', 1, 2];
// 읽기 전용
const arr: readonly number[] = [1, 2, 3];
const arr: readonlyArray<number> = [1, 2, 3];
Tuple (정해진 타입의 고정된 길이 배열)
const tuple: [string, number];
tuple = ['a', 1];
tuple = ['a', 1, 2]; // Error
tuple = [1, 'a'] // Error
// 튜플 타입의 배열(2차원 배열)
const users: [number, string, boolean][];
users = [[1, 'Cat', true], [2, 'Dog', false]];
// 할당할 때에만 정해진 타입의 고정된 길이 배열을 표현함
// .push() .splice() 등의 사용을 막을 수는 없음
const tuple: [string, number];
tuple = ['a', 1];
tuple.push(3);
console.log(tuple); // ['b', 2, 3]
tuple.push(true); // Error. string과 number 타입만 가능
Any (모든 타입)
어떤 타입의 값도 할당 가능
모든 다른 타입의 변수에 Any 타입의 값 할당 가능
되도록 사용하지 않는 것이 좋음
let any: any = 123;
any = 'Hello';
any = null;
const bool: boolean = any; // any는 모든 다른 타입에 할당 가능
Unknown (알 수 없는 타입)
어떤 타입의 값도 할당 가능
Any 를 제외한 다른 타입의 변수에 Unknown 타입의 값 할당 불가능
let un: unknown = 123;
un = 'Hello';
un = null;
const any: any = un;
const num: number = un; // Error. unknown은 any를 제외한 다른 타입에 할당 불가능
const num: number = un as number; // 타입 단언 시 할당 가능
Object (객체)
typeof 연산자가 "object" 로 반환하는 모든 타입
컴파일 옵션에서 strict를 true로 설정 시 null을 포함하지 않음
const obj: object = {};
const arr: object = [];
const func: object = function () {};
const nullVal: object = null;
const date: object = new Date();
...
// Object는 다른 타입들의 상위 타입이기 때문에 유용하지 않음
// 정확한 타입 지정을 위해 프로퍼티들의 타입을 개별적으로 지정할 수 있음
const user: { name: string, age: number } = {
name: 'Cat',
age: 12
};
// interface, type 을 사용할 수도 있음
interffacce User {
name: string,
age: number
};
const user: User {
name: 'Cat',
age: 12
};
Null / Undefined
모든 타입의 하위 타입임
모든 타입에 할당 가능
서로의 타입에도 할당 가능
컴파일 옵션 "strictNullChecks" : true 설정 시 서로의 타입에 할당 불가
(Void 에는 Undefined 할당 가능)
const num: number = undefined;
const str: string = null;
const obj: { a: 1, b: false } = undefined;
const arr: any[] = null;
const und: undefined = null;
const nul: null = undefined;
const voi: void = null;
...
Void
값을 반환하지 않는 함수에서 사용함
값을 반환하지 않는 함수는 undefined 를 반환함
리턴 타입이 Void, Any 가 아닌 함수는 return 문을 포함해야 함
function hello(msg: string): void {
console.log('Hello ${msg}');
}
const hi: void = hello('world'); // Hello world
console.log(hi); // undefined
Never
절대 발생하지 않을 값을 나타냄
어떤 타입도 적용 불가능
빈 배열을 타입으로 선언한 경우 never 타입이 됨
function error(msg: string): never {
throw new Error(msg);
}
Union (유니언)
2개 이상의 타입을 허용하는 경우의 타입
| 는 또는 을 의미함
const union: (string | number); // String 또는 Number 타입 허용
Intersection (인터섹션)
2개 이상의 타입을 조합하는 경우의 타입
& 는 그리고 를 의미함
// 기존 타입들이 조합 가능할 경우 인터섹션 활용 가능
interface User {
name: string,
age: number
}
interface Valid {
isValid: boolean
}
const cat: User & Valid = {
name: 'Cat',
age: 12,
isValid: true
}
Function (함수)
화살표 함수를 이용해 타입 지정 가능
(인수 타입) => 반환 타입
// 인수: 숫자 타입 2개, 반환 값: 숫자 타입
const func: (arg1: number, arg2: number) => number
func = function (x, y) {
return x + y;
}
// 인수 없음, 반환 값 없음
const func: () => void
func = function () {
console.log('nothing');
}
// 인터페이스로 함수 타입 지정 가능
interface Func {
(x: number, y: number): number
}
const func: Func = function (x, y) {
return x + y;
}