Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To define a generic type that can have any property of a specific type in TypeScript, you can use an index signature. For example:

type AnyObject<T> = {
  [key: string]: T;
};

Here, AnyObject is a generic type that can have any property of type T using the index signature [key: string]: T;.

You can use this type to define an object that can have any property of any type:

const obj: AnyObject<any> = {
  foo: "bar",
  age: 30,
  isAlive: true,
};

Or an object that can have any property of a specific type:

interface User {
  name: string;
  age: number;
}

const user: AnyObject<User> = {
  name: "John",
  age: 30,
};

In this case, AnyObject<User> specifies that the object can have any property of type User.