TypeScript Tips and Tricks 1

Many of us incorporate TypeScript into our projects, but are we fully aware of its extensive capabilities? While TypeScript is often recognized for its ability to define data types, its advanced functionalities open doors to a multitude of possibilities. For instance:
You can enforce strict parameter requirements for functions.
You can remove attributes from Object
TypeScript enables the creation of dynamic and adaptable data types.
Understanding these advanced features allows developers to harness the full potential of TypeScript in their projects.
Enforce strict parameter requirements for functions
let’s suppose that we have an Object like
const testObj = {
name: 'Jhon',
surname: 'Doe',
age: 28
}
we want to have a function that return value from key.
As a normal way we can use JavaScript function and make it easily but lets see in Typescript.
const getValueFromArray = (obj,key) => obj[key]
// in Type script, we can use it like:
const getValueFromArray =<T extends Object> (obj:T, key: keyof T): T[keyof T] => obj[key]
This usage is better than other, user will not be able to give key that does not in keys.
Remove attributes from Object
In JavaScript it is really easy to remove attribute from Object. When we use typescript, it can be better to remove attribute from type but HOW?
lets see how we are going to do this.
// in JS, we can do it like:
const removeKey = (obj, key) => delete obj[key]
// in typeScript we should use generic
const removeKey = <T extends Object, K extends keyof T>(obj: T, key: K): Omit<T, K> =>
delete obj[key] as any
In typescript, we should use two generic one is for object other one is for key. For the return type we will use Omit for removing key from the Object.
As an extra, we can apply same logic for removing attributes from array.
const removeKeys = <T extends Object, K extends keyof T>(obj: T, key: K[]): Omit<T, K> =>
{ return {} as any }
Summary
We should use typeof and keyof when we are working on Object
We should use const Object instead of enum to have better typescript experience.
Back