8. 타입 별칭 (type)
- 자주 쓰는 타입에 이름 부여
type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
- Union 타입에도 타입 별칭 부여 가능
type ID = number | string;
9. 인터페이스 (interface)
- 객체 타입 정의 방식 (type과 유사)
interface Point {
x: number;
y: number;
}
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
- interface는 확장 가능, 선언 병합 가능
interface vs type
타입은 새 프로퍼티를 추가하도록 개방될 수 없음
인터페이스의 경우 항상 확장될 수 있다.
인터페이스 확장
interface Animal { name: string } interface Bear extends Animal { honey: boolean } const bear = getBear() bear.name bear.honey교집합을 통해 타입 확장
type Animal = { name: string } type Bear = Animal & { honey: Boolean } const bear = getBear(); bear.name; bear.honey;기존의 인터페이스에 새 필드 추가
interface Window { title: string } interface Window { ts: TypeScriptAPI } const src = 'const a = "Hello World"'; window.ts.transpileModule(src, {});타입은 생성된 뒤에는 달라질 수 없다.
type Window = { title: string } type Window = { ts: TypeScriptAPI } // Error: Duplicate identifie타입 별칭은 선언 병합에 포함될 수 없지만, 인터페이스는 포함될 수 있습니다.
인터페이스는 오직 객체의 모양을 선언하는 데에만 사용되며, 기존의 원시 타입에 별칭을 부여하는 데에는 사용할 수는 없습니다.
인터페이스의 이름은 항상 있는 그대로 오류 메시지에 나타납니다. 단, 이는 오직 코드상에서 해당 인터페이스가 이름으로 사용되었을 때에만 해당합니다.
10. 타입 단언 (as)
- 타입스크립트보다 타입을 내가 더 잘 아는 경우
- ex) 페이지 상에서 사용되는 ID로는 언제나 HTMLCanvasElement 가 반환된다는 사실을 알고 있다면, 타입 단언을 사용하여 타입을 좀 더 구체적으로 명시
const canvas = document.getElementById("myCanvas") as HTMLCanvasElement;
- 타입 단언은 컴파일 시간에 제거되므로, 타입 단언에 관련된 검사는 런타임 중에 이루어지지 않습니다. 타입 단언이 틀렸더라도 예외가 발생하거나
null이 생성되지 않을 것입니다.
11. 리터럴 타입
- 리터럴 값 그 자체를 타입으로 사용하는 것
- 즉,
"hello"나42,true같은 구체적인 값을 타입으로 지정하는 것
let a: "hello" = "hello"; // ✅ 가능
a = "hello"; // ✅ 가능
a = "hi"; // ❌ 오류! "hi"는 타입 "hello"가 아님
사용 이유
- 특정한 값들만 허용하고 싶을때 사용, API 요청, 옵션 제한 같은 곳에서 자주 사용
유니언 타입과 리터럴 타입 → 많이씀
type Direction = "up" | "down" | "left" | "right";
function move(dir: Direction) {
// ...
}
move("up"); // ✅ OK
move("jump"); // ❌ Error
- “up”, “down” 등 몇 가지 값만 허용할 때, 유니언으로 묶어주면 깔끔함
- enum 비슷한 느낌으로 자주 사용
🚧 잠깐! 이게 string으로 추론된다고?
const req = { url: "https://example.com", method: "GET" };
function handleRequest(url: string, method: "GET" | "POST") {
// ...
}
handleRequest(req.url, req.method); // ❌ Error
- 왜 에러나냐면
req.method는 string으로 추론,"GET"이 아니라고 생각하는 것
해결법 1: 타입 단언
const req = { url: "https://example.com", method: "GET" as "GET" };
해결법 2: 전체를 상수로
const req = { url: "https://example.com", method: "GET" } as const;
as const는 객체 전체의 모든 값들을 리터럴 타입으로 고정
12. null, undefined
strictNullChecks설정하면 더 안전하게 사용 가능- 옵셔널 체이닝
?., 단언 연산자!사용 가능
function liveDangerously(x?: number | undefined) {
// 오류 없음
console.log(x!.toFixed());
}
13. 자주 사용되지 않는 원시형 타입
- 자바스크립트의 희귀 원시 타입도 지원
bigint
- 아주 큰 정수를 다루기 위한 원시 타입
symbol
- 전역적으로 고유한 참조값을 생성하는데 사용
- Symbol() 함수를 통하여 생성할 수 있다.
'Web > TypeScript' 카테고리의 다른 글
| [TypeScript 공식문서] 3. Narrowing (0) | 2025.03.25 |
|---|---|
| [TypeScript 공식문서] 2. Everyday Types(1) (1) | 2025.03.22 |
| [TypeScript 공식문서] 1. The Basics (1) | 2025.03.20 |