TypeScript #2 Generics
10166 ワード
Generics
function merge<T1, T2>(a: T1, b: T2) {
return {
...a,
...b
}
}
const merged = merge({foo: 1}, {bar: 2}); // merged에 마우스를 올리면 내부에 무엇이 있는지 볼 수 있다.
merged.foo // merged. 까지 치면 자동완성으로 내부에 있는 변수를 볼 수 있다.
つまり、どの値を入力するか分からないときにanyを使用すると、変数にマウスを置くとanyタイプ、Jennixを使用すると、入力値のタイプに応じて動的にどのタイプかを教えてくれます.次にもう一つの例を見ます.function wrap<T>(a: T) {
return {
a
}
}
const wrapped = wrap(30);
wrapped.a
Genericsをinterface,typeに適用する
interface
interface Items<T> {
list: T[];
}
const items: Items<string> { // 만약 Generics안에 number를 쓰게 되면 아래 문자열 배열은 빨간 줄이 뜬다.
list: ['a', 'b', 'c']
}
type
type Items<T> = {
list: T[];
}
const items: Items<string> {
list: ['a', 'b', 'c']
}
個数が多くても大丈夫です。
type Items<T, V> {
list: T[];
value: V
}
const items: Items<string, number> {
list: ['a', 'b', 'c'],
value: 1,
}
Genericsをクラスに適用しようとします class Queue<T> {
list: T[] = [];
// constructor(public list: T[]) {
// this.list = list;
// }
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}
const queue = new Queue<string>();
queue.enqueue('a');
console.log(queue.dequeue()); // a
Reference
この問題について(TypeScript #2 Generics), 我々は、より多くの情報をここで見つけました
https://velog.io/@joker77z/TypeScript-2-Generics
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
interface Items<T> {
list: T[];
}
const items: Items<string> { // 만약 Generics안에 number를 쓰게 되면 아래 문자열 배열은 빨간 줄이 뜬다.
list: ['a', 'b', 'c']
}
type Items<T> = {
list: T[];
}
const items: Items<string> {
list: ['a', 'b', 'c']
}
type Items<T, V> {
list: T[];
value: V
}
const items: Items<string, number> {
list: ['a', 'b', 'c'],
value: 1,
}
class Queue<T> {
list: T[] = [];
// constructor(public list: T[]) {
// this.list = list;
// }
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}
const queue = new Queue<string>();
queue.enqueue('a');
console.log(queue.dequeue()); // a
Reference
この問題について(TypeScript #2 Generics), 我々は、より多くの情報をここで見つけました https://velog.io/@joker77z/TypeScript-2-Genericsテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol