Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- API
- frontend
- SOLID
- DB
- postgresql
- Git
- DM
- ts
- PRISMA
- vscode
- UI
- js
- review
- Linux
- react
- threejs
- PyTorch
- C++
- Express
- nodejs
- CV
- figma
- CSS
- sqlite
- html
- ps
- python
- mongo
- GAN
- ML
Archives
- Today
- Total
아카이브
[TS] Syntax | 04. Interface 본문
Interface는 여러 개의 타입 묶음을 하나의 타입으로 취급하는 방법입니다.
이는 비슷한 종류의 객체들이 중복되는 타입 묶음들을 공유할 때 하나의 타입으로 간단하게 표현할 수 있도록 합니다.
아래 코드는 id, name, price, membersOnly 네 가지 변수에 대한 타입 묶음을 Product라는 하나의 새로운 타입으로 나타내는 interface를 구현했습니다.
interface Product {
id: string;
name: string;
price: number;
membersOnly?: boolean;
}
새롭게 정의한 Product를 이용하면 같은 객체 타입을 가지는 product1과 product2의 타입선언을 간단하게 표기할 수 있습니다.
const product1: Product = {
id: 'c001',
name: 'mug',
price: 129000,
membersOnly: true,
};
const product2: Product = {
id: 'd001',
name: 'shoes',
price: 25000,
};
interface는 상속도 가능합니다. 다음과 같이 extends 구문을 이용해 기존에 있던 interface 타입에 새로운 타입을 추가해 다시 정의할 수 있습니다.
enum Size {
S = 'S',
M = 'M',
L = 'L',
XL = 'XL',
}
interface ClothingProduct extends Product {
sizes: Size[];
}
const product3: ClothingProduct = {
id: 'e001',
name: 'T-shirts',
price: 19900,
sizes: [Size.S, Size.M],
};
interface를 이용해 함수의 타입도 정의할 수 있습니다.
(input arg: input type) => output type 형식으로 정의하던 타입을
(input arg: input type): output type 형식으로 정의할 수 있습니다.
interface PrintProductFunction {
(product: Product): void;
}
const printProduct: PrintProductFunction = (product) => {
console.log(`The price of ${product.name} is ${product.price}.`)
}
printProduct(product1);
printProduct(product2);
728x90
'Language > TypeScript' 카테고리의 다른 글
[TS] Syntax | 05. 타입 별칭(Type Alias) (1) | 2024.06.28 |
---|---|
[TS] Type | 02. Literal 타입 (1) | 2024.06.28 |
[TS] type | 01. 열거형(enum) (0) | 2024.06.28 |
[TS] Syntax | 03. 함수 타입 명시하기 (0) | 2024.06.24 |
[TS] Syntax | 02. 객체 타입 명시하기 (0) | 2024.06.24 |
Comments