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
- Swift
- AWS
- class component
- enum
- Kotlin
- collection
- CLASS
- vuex
- lifecycle
- docker-compose
- mongoose
- Filter
- union
- Generic
- function
- recyclerview
- animation
- docker
- ReactNative
- Foreign Key
- 생명주기
- elementAt
- LiveData
- Interface
- MINUS
- list
- map
- Service
- react native
- ConstraintLayout
Archives
- Today
- Total
개발 일기
Generics ? 본문
만약에 Generics을 사용하지 않았을 경우에는 다음과 같이 사용을 해야합니다.
function identity(arg: number): number {
return arg;
}
or
function identity(arg: any): any {
return arg;
}
하지만 위에 같이 any를 했을 경우에는 타입을 잃기 때문에 다음과 같이 Generic을 통해서 할수가 있습니다.
function identity<T>(arg: T): T {
return arg;
}
이제 사용은 다음과 같이 두가지 방법이 있습니다.
let output = identity<string>("myString");
let output = identity("myString"); // type of output will be 'string'
하지만 기본적으로 Generic은 모든 타입이 가능하기 때문에
function loggingIdentity<T>(arg: T): T {
console.log(arg.length); // Error: T doesn't have .length
return arg;
}
위와 같은 코드는 오류가 발생합니다.
그래서 위와 같은 코드에서는 다음과 같이 가능하도록 이렇게 변경해야합니다..
function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
혹은 다음과 같이도 변경할수가 있습니다.
function loggingIdentity<T>(arg: Array<T>): Array<T> {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
제네릭은 다음과 같이 유형을 표기할수가 있습니다.
interface GenericIdentityFn {
<T>(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn = identity
---
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: { <T>(arg: T): T } = identity;
---
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: <U>(arg: U) => U = identity;
---
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: <T>(arg: T) => T = identity;
Class Generic
Typescript에서 Generic Class는 다음과 같이 표시가 가능합니다.
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) {
return x + y;
};
그리고 다음과 같이 제약조건을 걸수가 있습니다.
class BeeKeeper {
hasMask: boolean;
}
class ZooKeeper {
nametag: string;
}
class Animal {
numLegs: number;
}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nametag; // typechecks!
createInstance(Bee).keeper.hasMask; // typechecks!
'컴퓨터 언어 > Typescript' 카테고리의 다른 글
Enums ? (0) | 2020.05.12 |
---|---|
Unions and Intersection Types ? (0) | 2020.05.10 |
Literal Types ? (0) | 2020.05.03 |
Function ? (0) | 2020.05.03 |
Class ? (0) | 2020.05.01 |
Comments