[230614] TypeScript 공식문서 (More on Functions)
1. Typescript More on Functions 정독 완료
- 공식문서 More on Functions 부분 정독 완료
- 학습 페이지 - More on Functions
제네릭 함수
function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}
함수 오버로드
가능하면 오버로드 대신 유니온 타입을 사용해라고함
function len(s: string): number;
function len(arr: any[]): number;
function len(x: any[] | string): number;
function len(x: any) {
return x.length;
}
console.log(len("")); // OK
console.log(len([0])); // OK
len(Math.random() > 0.5 ? "hello" : [0]);
함수 내 this
선언
interface User {
id: number;
admin: boolean;
}
declare const getDB: () => DB;
// ---cut---
interface DB {
filterUsers(filter: (this: User) => boolean): User[];
}
const db = getDB();
const admins = db.filterUsers(function (this: User) {
return this.admin;
});
//화살표 함수는 안됨
const admins = db.filterUsers(() => this.admin);
void
- 아무것도 반환하지 않는 함수는 암묵적으로
undefined
값을 반환합니다. 하지만 TypeScript에서void
와undefined
는 같은 것으로 간주되지 않습니다.
Leave a comment