In this post, you will learn 15 useful typescript tips and tricks that will improve your productivity and ensure fewer bugs in your code.
1. Don’t use (as) for better type checking
type User = { name: string; age: number; email: string;}const user = { name: ‘John Doe’, age: 30} as User;
This won’t throw any error for not giving the `email` property. In order to ensure type checking write like this,
type User = { name: string; age: number; email: string;}const user: User = { name: ‘John Doe’, age: 30};
2. Use (as) for immutability
const values = [1, 2, 3];values.push(4);console.log(values); // [1, 2, 3, 4]
In order to make the values array immutable or make it read-only, you can use `as`
const values = [1, 2, 3] as const;values.push(4); // Property 'push' does not exist on type 'readonly [1, 2, 3]'console.log(values);
The same goes for objects also,
const user = { name: ‘john’} as const;user.name = ‘david’;
cannot assign to ‘name’ because it is a read-only property
3. Use record utility when creating a dynamic object or the property type is unknown
type Profile = Record<string, unknown>;const profile: Profile = { id: 12, name: 'Brock'}
4. Use pick utility when constructing a new type from a given type
type User = { name: string; age: number; email: string;}const sendEmail = (arg: Pick<User, "name" | "email">) => { console.log(arg); // { name: 'John', email: 'john@gmail.com' }}const user = { name: 'John', email: 'john@gmail.com'}sendEmail(user);
5. Use Generics to ensure the function’s reusability
function removeItem<T>(arr: Array<T>, item: T): Array<T> { const index = arr.findIndex(value => value === item); arr.splice(index, 1); return arr;}removeItem([1, 2, 3], 3);removeItem([‘PHP’, ‘JavaScript’, ‘Python’], ‘PHP’);
Now arr can be an array of strings or array of numbers and an item can be a number or string, we can reuse the removeItem function.
6. Use partial to make every property type optional
type Post = { id: number; title: string; body: string;}const post: Partial<Post> = { title: “This is my first post”}
In this example, the `id`, and `body` is ignored, since it is Partial<Post>.
7. Use Indexed Access Type to lookup for a specific property from a type
type Message = { id: number; body: string; sender: { name: string; email: string; }}type MessageSender = { info: Message[‘sender’];}
In this example, we are getting the sender type using typeScript’s indexed access type.
8. Use Type Guards when you are using the union of types
function showMessage(message: string | object): void { if (typeof message === "string") { console.log("The type is string"); } else if (typeof message === "object") { console.log("The type is object"); }}showMessage({ name: "John Doe" });
Just like `typeof`, typescript also provides `in` type guard,
type User = { name: string; age: number;}type UserAddress = { house_no: number; state: string; city: string;}const main = (obj: User | UserAddress) => { if(‘name’ in obj) { processUser(obj); } else { processAddress(obj); }}main({ name: ‘John’, age: 24 });
9. Avoid making property optional when it isn’t valid instead create a new type with omitted utility
type Post = { id: number; title: string; body: string; category: string;}const savePost = (obj: Omit<Post, “category”>) => {}
A single post may not have category property but it still needs to be processed.
10. Specify each API’s type separately
// don’t do like thistype GitHubAndSlackAPI = { id: string; title: string; body: string; created_at?: Date}// instead do like thistype GitHubPRApi = { id: string; title: string; body: string; created_at: Date}type SlackApi = { id: string; title: string; body: string;}
In this way, we can add more information for each API efficiently.
These are the 10 typescript tips and tricks.
Credit
This post was written by one of the best software engineers at Technext — Muhammad Lahin.
Technext helps startups and businesses hire great software engineers.
You can hire an offshore software development team from Technext.
Please visit the services we offer as offshore software development services for your startups.
Have any projects?
Reach out to hire the brilliant software engineering and UI/UX design team. Build your dream projects.
Let’s collaborate
Speak with our leadership team directly.
https://bd.linkedin.com/in/syed-rezwanul-haque-b7889628
- https://technext.it
- reza@technext.it
- +8801717141905