1. 기본 사용법
TypeScript에서 선언 병합(Declaration Merging)은 여러 개의 선언이 동일한 이름을 가질 때, 이를 결합하여 하나의 선언으로 만드는 타입스크립트 기능입니다. 기본 사용법은 Typescript는 같은 이름의 인터페이스나 네임스페이스를 여러 번 선언할 수 있으며, 이들을 자동으로 병합합니다.
interface User {
name: string;
age: number;
}
interface User {
email: string;
phone: string;
}
const user: User = {
name: 'John Doe',
age: 25,
email: 'aaa@aaa.com',
phone: '123456789',
};
2. 인터페이스 병합
여러 개의 인터페이스가 같은 이름을 가지면, TypeScript는 모든 프로퍼티를 결합합니다.
interface Option {
name: string;
}
interface Option {
size: number;
}
const option: Option = {
name: 'Full-Size',
size: 1920 * 1080,
};
console.log(option); // { name: 'Full-Size', size: 2073600 }
3. 네임스페이스 병합
네임스페이스도 같은 이름을 가질 경우 병합됩니다.
namespace Shapes {
export interface Circle {
radius: number;
}
}
namespace Shapes {
export interface Square {
sideLength: number;
}
}
const myCircle: Shapes.Circle = { radius: 10 };
const mySquare: Shapes.Square = { sideLength: 5 };
console.log(myCircle, mySquare); // { radius: 10 } { sideLength: 5 }
4. 네임스페이스와 클래스 병합
클래스와 네임스페이스를 결합할 수 있습니다. 이 경우 클래스의 인터페이스와 정적 프로퍼티를 사용할 수 있습니다.
class Person {
static species = 'Homo sapiens';
constructor(public name: string) {}
}
namespace Person {
export function greet(person: Person) {
console.log(`Hello, ${person.name}`);
}
}
const kahn = new Person('Kahn');
Person.greet(kahn); // "Hello, Kahn"
5. 허용되지 않는 병합
- 모듈 보강: 모듈 내에서 같은 이름의 변수를 여러 번 선언하는 것은 허용되지 않으며, 모듈은 서로 다른 스코프를 가지기 때문에 병합되지 않음
// Error: Duplicate identifier 'x'.
const x = 10;
const x = 20; // Error: Cannot redeclare block-scoped variable 'x';
- 전역 보강: 전역 스코프에서 같은 이름의 변수나 타입을 여러번 선언하는 것도 허용하지 않음
// Error: Duplicate identifier 'y'.
var y = 10;
var y = 20; // Error: Cannot redeclare block-scoped variable 'y';
GitHub - Koras02/typescript-bloging
Contribute to Koras02/typescript-bloging development by creating an account on GitHub.
github.com
LIST
'Front-End > TypeScript' 카테고리의 다른 글
[TypeScript] 14장 유티릴티 타입 (1) | 2025.03.20 |
---|---|
[Typescript] 13장 데코레이터 (0) | 2025.03.14 |
[Typescript] 11장 고급 타입 Chapter 2 (0) | 2025.03.08 |
[Tyepscript] 10장 고급 타입 Chapter 1 (0) | 2025.03.06 |
[Typescript] 9장 제네릭 (0) | 2025.02.24 |