티스토리 뷰
728x90
// generic vs. any
function hello(message: any): any {
return message;
}
console.log(hello('Hyun').length);
console.log(hello(33).length)
function helloGeneric<T>(message: T): T {
return message;
}
console.log(helloGeneric<string>('Hyun').length); // T는 string
console.log(helloGeneric('Hyun').length); // T는 'Hyun'
console.log(helloGeneric<number>(33).length); // T는 number
// any를 사용하면 못 잡던 error를 잡아 준다.
console.log(helloGeneric(33).length); // T는 33
// any를 사용하면 못 잡던 error를 잡아 준다.
// generic 기본
function helloBasic<T, U>(message: T, comment: U): T {
return message;
}
helloBasic<string, number>("Hyun", 33);
helloBasic(33, 34);function helloBasic<T, U>(message: T, comment: U): T {
return message;
}
helloBasic<string, number>("Hyun", 33);
helloBasic(33, 34);
// Generic Array & Tuple
const genericArray = <T>(message: T[]): T => {
return message[0];
}
const genericTuple = <T, K>(message: [T, K]): T => {
return message[0];
}
// Generic Function
interface IFunction {
(message: string): string;
}
const helloIFunction: IFunction = (message: string): string => {
return message;
};
type TFunction = (message: string) => string;
const helloTFunction: TFunction = (message: string): string => {
return message;
};
interface IGFunction {
<T>(message: T): T;
}
const IGfunc: IGFunction = <T>(message: T): T => {
return message;
};
type TGfunction = <T>(message: T) => T;
const TGfunc: TGfunction = <T>(message: T): T => {
return message;
};
// Generic Class
class Person<T, K> {
constructor(private _name: T, private _age: K) {}
}
const p1 = new Person('Hyun', 33);
const p2 = new Person<string, number>('Hyun', 33);
// Generic extends - 제네릭에서의 타입 제한
class Person<T extends string | number> {
constructor(private _name: T) {}
}
const p1 = new Person('Hyun');
const p2 = new Person(33);
const p3 = new Person(true); // Error
'웹 개발 > Typescript' 카테고리의 다른 글
Nextjs window.ethereum, environment variable 타이핑 (0) | 2022.01.16 |
---|---|
keyof + generic + extends & type lookup (0) | 2022.01.08 |
class 기본 (static, singleton) (0) | 2022.01.08 |
class 기본 (readonly, index signatures) (0) | 2022.01.04 |
class 기본 (초기화, getter, setter) (0) | 2022.01.04 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- ERC721
- class
- web3.js
- 앱 아이콘
- caver-js
- 스마트 컨트랙트
- Android
- JWT
- 블록 탐색기
- swr
- metamask-extension
- Call
- Hardhat
- interface
- Truffle
- Proxy Pattern
- web3-token
- ethers.js
- ganache
- typescript
- erc20
- 이더리움
- Upgradeable Contracts
- nft
- Flutter
- caver.js
- eslint
- avalanchego
- web3
- 블록체인
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함