유틸리티
파이프, 선택적, 확신적 선언
type Alphabet = "A" | "B" | "Z";
const alphaB: Alphabet = "B";
const alphaD: Alphabet = "D"; // Error
파이프| 문법으로 타입이 여러개 할당될 수 있음을 표현할 수 있다. 위 예시에서는 "A", "B", "C" 중 하나를 할당할 수 있음을 나타낼 수 있다. 이렇게 문자 뿐만 아니라 Primitive 자료형을 값 그대로 표현하는 타입을 리터럴 타입이라고도 한다.
type SomeObject = {
id: string;
multiple?: boolean;
}
const justId: SomeObject = {
id: "xxx",
}
const multiple: SomeObject = {
id: "xxx",
multiple: true
}
필드를 정의할 때 ? 문법을 사용하여 해당 필드가 있든 없든 허용할 수 있다. 사실 이 문법은 multiple: boolean | undefined의 축약형이다. 그래서 필드가 없거나 undefined는 가능하지만 isNaN, null, "" 등의 값은 할당할 수 없다.
const el = document.querySelector("div"); // HTMLDivElement | null
console.info(el!.textContent);
비슷한 문법으로 ! 가 있는데 이 문법은 런타임 코드에서 사용된다. el 변수가 null일 가능성이 있는 경우 타입스크립트는 el.textContent 코드에서 오류'element' is possibly 'null'를 발생시킨다. 이 코드가 동작할 시점에 el 변수가 반드시 존재한다고 확신할 수 있다면 ! 를 사용하여 타입스크립트 컴파일러에게도 알려줄 수 있다.
extends
type Alpha = "A";
type Numeric = 0 | 1;
class Animal {
constructor() { }
}
class Dog extends Animal {}
class Cat extends Animal {}
type Conditional<T = Alpha> = T extends Alpha ? Numeric : Alpha;
type Conditional<T = Animal> = T extends Animal ? Numeric : Alpha;
extends 문법은 인터페이스나 클래스를 확장할때도 사용하지만 위처럼 지네릭의 분기문으로도 사용할 수 있다. 3항 연산자조건 ? 참 : 거짓와 사용법은 동일하다. 다양한 조건을 주기는 힘들지만 타입을 좀 더 동적으로 만들 수 있는 문법이다.
Pick & Omit
interface User {
username: string;
password: string;
name: string;
mail: string;
}
type UserLoginInfo = Pick<User, "username" | "password">;
type UserProfile = Omit<User, "username" | "password">;
const loginInfo: UserLoginInfo = {
username: "luasenvy",
password: "Passw0rd",
};
const profile: UserProfile = {
name: "luasenvy",
mail: "luas.envy@gmail.com",
};
지정한 키만을 선택하거나 제외시킨 타입을 만들 수 있다. 객체형 뿐만 아니라 다양한 형태의 타입에 적용하여 사용할 수 있다.
Parameters & ReturnType & Awaited
type CallbackFunction = () => Promise<number>;
const asyncFn: CallbackFunction = async (a: number) => a + 10;
const firstParameter: Parameters<CallbackFunction>[0] = 30;
const returnTypeResult: ReturnType<CallbackFunction> = Promise.resolve(40);
const awaitedResult: Awaited<ReturnType<CallbackFunction>> = 50;
- Parameters: 함수의 파라미터 타입을 선택할 수 있다.
- ReturnType: 함수의 반환 타입을 선택할 수 있다.
- Awaited: 함수가 Promise로 작성되어있을 경우 Promise의 지네릭을 선택할 수 있다.
keyof & typeof
enum UserType {
"member",
"admin",
"sysadmin",
"operator",
"guard",
"bot",
}
interface User {
username: string;
password: string;
name: string;
mail: string;
type: UserType;
}
class Account implements User {
username: string;
password: string;
name: string;
mail: string;
type: UserType;
constructor(username: string, password: string, name: string, mail: string, type: UserType) {
this.username = username;
this.password = password;
this.name = name;
this.mail = mail;
this.type = type;
}
}
type UserPropertyKeys = "username" | "password" | "name" | "mail";
type UserPropertyKeyofKeys = keyof User;
const account: Account = new Account(
"luasenvy",
"Passw0rd",
"luasenvy",
"luas.envy@gmail.com",
UserType.member
);
const typeofAccount: typeof account = account;
- keyof: 뒤에 명시하는 타입의 키들을 선택할 수 있다.
- typeof: 뒤에 명시하는 값의 타입을 선택할 수 있다.