type an object with string values in typescript

To type an object with string values in TypeScript, you can use the following syntax:

index.ts
type MyObject = {
  [key: string]: string;
}
45 chars
4 lines

This defines a type MyObject that has string values associated with each key. You can then use this type to specify the type of an object that has string values for any arbitrary key.

Here is an example of how to use MyObject type:

index.ts
const obj: MyObject = {
  name: "John",
  age: "25",
  email: "john@example.com",
};

console.log(obj.name); // "John"
console.log(obj.age); // "25"
console.log(obj.email); // "john@example.com"
195 chars
10 lines

In the above example, obj is of type MyObject and has string values associated with each key. You can access the values of any key using the dot notation.

gistlibby LogSnag