Posts > TS Basic: Utilities
March 19, 2025
Type utilities you can use to transform types or make them more reusable. These are set of built-in generic types.
Here are common I’ve used so far.
Type
to use and key
or property to remove / omittype User = {
name: 'string',
age: 'number',
id: 'string',
}
type UserDetails = Omit<User, 'id'>
const user: UserDetails = {
name: 'Owa',
age: 25,
}
Type
to use and key
to retaintype User = {
name: 'string',
age: 'number',
id: 'string',
}
type UserId= Pick<User, 'id'>
const user: UserId = {
id: '111184',
}
type UserInfo = {
name: string;
age: number;
location: string;
};
type UserDatabase = Record<string, UserInfo>;
const users: UserDatabase = {
'user123': {
name: 'Alice',
age: 30,
location: 'New York',
},
'user456': {
name: 'Bob',
age: 25,
location: 'London',
},
'user789': {
name: 'Charlie',
age: 35,
location: 'Tokyo',
},
};
// Accessing the data
console.log(users['user123'].name); // Output: Alice
console.log(users['user456'].age); // Output: 25
//Another example with number keys.
type NumberedRecord = Record<number, string>;
const numberRecord: NumberedRecord = {
1: "one",
2: "two",
3: "three"
};
console.log(numberRecord[2]); //output: two
//Another example with union types for keys.
type KeyUnion = 'a' | 'b' | 'c';
type UnionRecord = Record<KeyUnion, number>;
const unionRecord: UnionRecord = {
'a': 10,
'b': 20,
'c': 30
};
console.log(unionRecord.b); //output: 20
readonly
meaning the properties of the type cannot be reassigned.interface Todo {
title: string,
}
const todo: Readonly<Todo> = {
title: 'Delete me',
}
todo.title = 'Hello' // type error Cannot assign to 'title' because it is a read-only property.
👌More Utility Types on typescript docs https://www.typescriptlang.org/docs/handbook/utility-types.html