Murray  Beatty

Murray Beatty

1595774760

Overriding Inheritance in New Types Using Omit and Keyof in Typescript

TypeScript can be weird and not very intuitive. Pardon me, I started learning TypeScript in January 2020. And JavaScript programming since 2018, almost two years. Not the little scripts we write in with libraries like JQuery and in small files to manipulate HTML pages but JavaScript as a full fledged programming language to build libraries and code off any framework/library written in JavaScript. For everyone abreast of developments in the JavaScript world, learning TypeScript is imperative. Deno the new JavaScript and TypeScript runtime has first class support for TypeScript.

What is helping me in learning TypeScript is my knowledge of Java. Java is statically typed and that’s what TypeScript is out to achieve for JavaScript. Compile time type checking. Types and Interfaces are used to derive objects that conform to specific types. As we all know TypeScript is a turing complete programming language.

The Famous Type

Let’s cut to the chase. Here we go:

type ModelFields<T> = Partial<Omit<T, keyof BaseModel>> & {
   created_at?: Date;
   updated_at?: Date;
};

For an intermediate or expert TypeScript programmer. This ModelFieldstype is simple.

It means, Pick the properties of generic type T and exclude all properties of BaseModel and use the intersection type and include created_at and updated_at and we have a brand new type.

#typescript #javascript #inheritance #stackoverflow #programming

Overriding Inheritance in New Types Using Omit and Keyof in Typescript