Posts > TS Basic: Utilities

TS Basic: Utilities

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.

Omit<Type, Keys>

  • creates a new type by excluding specific properties from an existing type
  • Type to use and key or property to remove / omit
type User = {
	name: 'string',
	age: 'number',
	id: 'string',
}

type UserDetails = Omit<User, 'id'>

const user: UserDetails = {
	name: 'Owa',
	age: 25,
}

Pick<Type, Keys>

  • creates a new type by selecting a specific properties from an existing type
  • Type to use and key to retain
type User = {
	name: 'string',
	age: 'number',
	id: 'string',
}

type UserId= Pick<User, 'id'>

const user: UserId = {
	id: '111184', 
}

Record<Keys, Type>

  • create an object type with specific keys and values
  • this utility can be used to map the properties of a type to another type
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<Type>

  • sets type type to 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