[typesciprt] Generic

hansol yang
1 min readFeb 23, 2020

--

I’ve always been confused about Generic..
but, I think I understand a little bit about Generic, so I record it.
Generic can be used when you have a difficult specifying the types, or when you want to be compatible with several types.

For example with code.

function merge<A, B>(a: A, b: B): A & B {
return {
...a,
...b
}
}
const merged = merge({ foo: 1 }, { bar: 1 });

The code above allows the IDE to understand the type by arguments type.
In this case, the arguments type is number, so the types of A, B will be numbers.
so cool!

In type, for below.

type Items<T> = {
list: T[];
}
const items: Items<string> = {
list: ["a", "b", "c"]
};

In this case, In items, specify Items’s type for string. so Items’s T is will be string, and list is will be string[].
interface is working same way.

You can also use Generic to match types in several places.
In this case, specify T as Generic and use it as a type where the T is commonly used for compatibility.

class Queue<T> {
list: T[] = [];
get length() {
return this.list.length;
}
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}

More details here! check that blog!

[reference]: https://velog.io/@velopert/typescript-basics

--

--

No responses yet