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 |
Tags
- ps
- js
- Git
- API
- vscode
- python
- frontend
- ts
- ML
- GAN
- postgresql
- review
- Linux
- Express
- sqlite
- UI
- SOLID
- CV
- PRISMA
- DM
- react
- C++
- CSS
- mongo
- html
- PyTorch
- nodejs
- figma
- DB
- threejs
Archives
- Today
- Total
아카이브
[TS] Syntax | 03. 함수 타입 명시하기 본문
함수를 선언할 때는 매개변수와 반환값의 타입을 명시해줍니다.
마찬가지로 코드에서 충분히 추론이 가능하다면 반환값의 타입은 명시하지 않아도 됩니다.
const stock: { [id: string]: number } = {
c001: 3,
c002: 1,
};
const cart: string[] = [];
function getItem(item: string): string {
return item;
}
매개변수의 디폴트값은 다음과 같이 나타냅니다.
function addToCart(id: string, quantity: number = 1) {
if (stock[id] < quantity) {
return false;
}
stock[id] -= quantity;
for (let i = 0; i < quantity; i++) {
cart.push(id);
}
return true;
}
가변변수는 다음과 같이 나타냅니다.
function addManyToCart(...ids: string[]) {
for (const id of ids) {
addToCart(id);
}
}
함수를 객체의 property에 포함할 때는 다음과 같이 화살표 표기법(=>)으로 타입을 명시합니다.
const mall: {
stock: { [id:string]: number }
cart: string[];
addToCart: (id:string, quantity?:number) => boolean;
addManyToCart: (...ids: string[]) => void;
} = {
stock: {
c001: 3,
c002: 1,
},
cart: [],
addToCart,
addManyToCart,
}
728x90
'Language > TypeScript' 카테고리의 다른 글
[TS] Syntax | 04. Interface (0) | 2024.06.28 |
---|---|
[TS] type | 01. 열거형(enum) (0) | 2024.06.28 |
[TS] Syntax | 02. 객체 타입 명시하기 (0) | 2024.06.24 |
[TS] Syntax | 01. 변수 타입 명시하기 (0) | 2024.06.24 |
[TS] TSC에 대해서 (0) | 2024.06.24 |
Comments