create type of keys of object in typescript

You can define an object type with a specific set of keys using an interface or type alias. For example, if you want to define an object that has a name key with a string value and an age key with a number value, you can do the following:

index.ts
interface MyObject {
  name: string;
  age: number;
}

const myObject: MyObject = {
  name: 'Alice',
  age: 30,
}
114 chars
10 lines

If you don't want to define a new type or interface, you can use an index signature to specify the object keys dynamically. For example:

index.ts
type MyObject = {
  [key: string]: string | number;
}

const myObject: MyObject = {
  name: 'Alice',
  age: 30,
}
114 chars
9 lines

In this example, the type of key is string, which means any string key can be used, and the values can be either string or number.

Note that using an index signature means that any key is allowed, whereas using an interface or type alias allows you to define a specific set of keys.

related categories

gistlibby LogSnag