Typescript: Utility Type
When we define a Typescript target from tsconfig.ts, for example, ES5, ES6 then the compiler includes a global definition file with an identical name, for example, lib.es5.d.ts or lib.es6.d.ts. Those files contain common utility types for us to use in our applications. Let’s explore utility types and how to use them in the practical case.
- Record
If you want to define an object type that contains keys and values, we should use Record.
type ServerValue = string | number | boolean;
const ServerConfig:Record<string, ServerValue> = {
ServerName: 'Microsoft',
ip:1921568214,
isActive: false
}
console.log(ServerConfig.ip) // return 19121568214
another problem is the key type of the record would be anything, it could be string, boolean, number, or anything, in best practice
we can specify a type that provides a list of allowed keys for this parameter using the union
type serverKey = 'serverName' | 'ip' | 'isActive'
const serverConfigK:Record<serverKey, serverValue> = {
serverName: 'Microsoft',
ip:1921568214,
isActive: false,
}
console.log(serverConfigK.isActive) //return false
2. Partial
If we have a type but want to create another type with all property keys as optional, then you can use the Partial type. It is helpful to declare classconstructor parameters with default values.
enum PRIORITY{
DEFAULT,
LOW,
HIGH
}
interface TodoItemProps {
title:string,
description:string,
priority:PRIORITY
}
class TodoItem {
description ?:string;
title = "Default item title";
priority = PRIORITY.DEFAULT
constructor (todoItemProps:Partial<TodoItemProps> = {}) {
Object.assign(this, todoItemProps)
}
}
const item = new TodoItem({})
3. Pick
if you have a type and you want to create another type by only specifying a property of the previous type then we can use the pick type
this is quite effective in cases when you have a fat interface and you want to extract part of its properties for use in your component.
for example, Use case when you define a React button containing only specific properties.
type Props = Pick<HTMLAttributes<HTMLButtonElement>, 'onclick'|'onSubmit'|'className'|'onFocus'>
4. Omit
This is the exact opposite of the Pick type. we utilize this type to generate another type with the specified property or properties excluded froth this list instead.
type DontTouchType = {
colors:string[],
margins:string[],
font:string[],
typegraply:string
}
type customeType {
colors:Set<string>
}
type myType = Omit<DontTouchType, 'colors'> & {colors:customeType};
Here we have an existing DontTouchType but want to utilize a slightly similar one with the custom colors property which is changed. We use Omit to create
A new type with this property was removed and subsequently, we use an intersection type to add a new color property.