Ask Your Question
2

How can one define a generic type that can have any property of a specific type in Typescript?

asked 2023-05-06 20:10:23 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-06 20:36:02 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-06 20:10:23 +0000

Seen: 11 times

Last updated: May 06 '23