Generic Comparison

This lesson explains the difference between comparing two generic types and two primitive types.

We'll cover the following

Generic and typeof

The generic code does not allow the use of typeof on T, type new T, or instanceof T.

The reason is that the transpilation step removes all traces of type. TypeScript transpiles typeof and instanceof operations into JavaScript, and during that step, it erases types. The absence of type at runtime justifies the lack of generic type verification at runtime as well.

The Generic solution

To compare two generics, we need to keep in mind that the types are erased (removed) when TypeScript is transpiled to JavaScript. Thus, we need to create a custom generic array with a unique identifier (or many) for comparison. For example, we can add an id field and have that value, not erased at runtime, be compared.

Get hands-on with 1400+ tech skills courses.