개요
TypeScript는 JavaScript에 정적 타입 검사를 추가합니다. 아래 예제에는 독립적인 타입 조각과 생략 기호가 포함되어 있으며, 하나의 소스 파일이 아닙니다. 타입 단언은 런타임 데이터 검증을 수행하지 않습니다.
기본 타입
any
void
boolean
number
string
null
undefined
bigint
symbol
string[] /* or Array<string> */
[string, number] /* tuple */
string | null | undefined /* union */
never /* unreachable */
unknown
enum Color {
Red,
Green,
Blue = 4
};
let c: Color = Color.Green
선언
let isDone: boolean
let isDone: boolean = false
function add (a: number, b: number): number {
return a + b
}
// Return type is optional
function add (a: number, b: number) { ... }
타입 단언
변수
let len: number = (input as string).length
let len: number = (<string> input).length /* not allowed in JSX */
함수
function object(this: {a: number, b: number}, a: number, b: number) {
this.a = a;
this.b = b;
return this;
}
// this is used only for type declaration
let a = object.call({ a: 0, b: 0 }, 1, 2);
// a has type {a: number, b: number}
인터페이스
인라인 타입
function printLabel (options: { label: string }) {
console.log(options.label)
}
// Note the semicolon
function getUser (): { name: string; age?: number } {
return { name: "Ada" };
}
이름이 있는 인터페이스
interface LabelOptions {
label: string
}
function printLabel(options: LabelOptions) { ... }
선택적 프로퍼티
interface User {
name: string;
age?: number;
}
읽기 전용 프로퍼티
interface User {
readonly name: string
}
인덱스 시그니처
{
[key: string]: Object[]
}
타입 별칭
타입 별칭
type Name = string | string[]
교차 타입
interface Colorful { ... }
interface Circle { ... }
type ColorfulCircle = Colorful & Circle;
함수 타입
interface User { ... }
function getUser(callback: (user: User) => any) { callback({...}) }
getUser(function (user: User) { ... })
클래스
class Point {
x: number
y: number
static instances = 0
constructor(x: number, y: number) {
this.x = x
this.y = y
}
}
상속
class Point {...}
class Point3D extends Point {...}
interface Colored {...}
class Pixel extends Point implements Colored {...}
매개변수 프로퍼티
class Point {
static instances = 0;
constructor(
public x: number,
public y: number,
){}
}
확정 할당 단언
class Point {
public someUselessValue!: number;
...
}
제네릭
class Greeter<T> {
greeting: T
constructor(message: T) {
this.greeting = message
}
}
let greeter = new Greeter<string>('Hello, world')
모듈
export interface User { ... }
인덱스 접근 타입
interface Building {
room: {
door: string;
walls: string[];
};
}
type Walls = Building['room']['walls']; // string[]
keyof 연산자
type Point = { x: number; y: number };
type P = keyof Point; // x | y
조건부 타입
// SomeType extends OtherType ? TrueType : FalseType;
type ToArray<T> = T extends any ? T[] : never;
type StrArrOrNumArr = ToArray<string | number>; // string[] | number[]
타입 추론
type GetReturnType<T> = T extends (...args: any[]) => infer R
? R
: never;
type Num = GetReturnType<() => number>; // number
type First<T extends Array<any>> = T extends [infer F, ...infer Rest] ? F : never;
type Str = First<['hello', 1, false]>; // 'hello'
리터럴 타입
const point = { x: 4, y: 2 }; // { x: number, y: number }
const literalPoint = { x: 4, y: 2 } as const; // { readonly x: 4, readonly y: 2 };
템플릿 리터럴 타입
type SpaceChar = ' ' | '\n' | '\t';
type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;
type Str = TrimLeft<' hello'>; // 'hello'
알 수 없는 타입의 입력 검증
function upper(value: unknown): string {
if (typeof value !== "string") throw new TypeError("Expected a string");
return value.toUpperCase();
}
any는 검사를 건너뛰며 unknown은 타입 좁히기가 필요합니다. 확정 할당 단언 !는 런타임에 필드를 초기화하지 않습니다.