함수를 선언할 때는 매개변수와 반환값의 타입을 명시해줍니다.
마찬가지로 코드에서 충분히 추론이 가능하다면 반환값의 타입은 명시하지 않아도 됩니다.
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 |