any 와 generic
function helloString(message: string): string {
return message;
}
function helloNumber(message: number): number {
return message;
}
function hello(message: any): any {
return message;
}
console.log(hello("Mark").length);
console.log(hello(39).length);
function helloGeneric<T>(message: T): T {
return message;
}
console.log(helloGeneric("Mark").length);
type 추론
string
function helloBasic<T>(message: T): T {
return message;
}
helloBasic<string>("Mark");
helloBasic(36);
function helloBasic2<T, U>(message: T, comment: U): T {
return message;
}
helloBasic2<string, number>("Mark", 39);
helloBasic2(36, 39);
array 와 tuple
function helloArray<T>(message: T[]): T {
return message[0];
}
helloArray(['hello', 'world']);
helloArray(['hello', 5]);
function helloTuple<T, K>(message: [T, K]): T {
return message[0]
}
helloTuple(['hello', 'world']);
helloTuple(['hello', 5]);
type alias 와 interface
type HelloFunctionGeneric1 = <T>(message: T) => T;
const helloFuntion1: HelloFunctionGeneric1 = <T>(message: T): T => {
return message;
}
interface HelloFunctionGeneric2 {
<T>(message: T): T
}
const helloFuntion2: HelloFunctionGeneric2 = <T>(message: T): T => {
return message;
}
class
class Person<T> {
private _name: T;
constructor(name: T) {
this._name = name;
}
}
new Person("Mark");
new Person(39);
new Person<string>(39);
--------------------------------------------------
class Person2<T, K> {
private _name: T;
private _age: K;
constructor(name: T, age: K) {
this._name = name;
this._age = age;
}
}
new Person2("Mark");
new Person2("Mark", 39);
new Person2<string, number>("Mark",39);
generic extends
class PersonExends<T extends string | number> {
private _name: T;
constructor(name: T) {
this._name = name;
}
}
new PersonExends("Mark");
new PersonExends(39);