Guy Bartkus
Guy Bartkus

Reputation: 45

Create a typing only for some properties of an object

Is there a way to only specify the type for some properties of an object instead of all? For example, if I have some object like

const user_account = {id: 37593, created: "23/04/2020", last_active: "23/04/2020"};

and I only wanted to specify id to be of type number, and everything else kept as any, is there a way to do this? Thanks.

Upvotes: 0

Views: 62

Answers (1)

jcalz
jcalz

Reputation: 330411

You can use a string index signature to represent that all the properties conform to a particular value type; in your case, any. Any named properties you add to the object outside the index signature must still conform to that type, but you can make them more specific. Since number is more specific than any, you can represent your type like { [k: string]: any; id: number }.

So

const settings: { id: number, [k: string]: any } = 
  {id: 37593, created: "23/04/2020", last_active: "23/04/2020"};

should work for you, depending on your use case. Note that such an annotation will widen the type of settings to the annotated type, so the compiler will not remember anything not specified in that type:

settings.id; // known to be number
settings.created; // only known as any, not string
settings.randomPropName; // also known as any

Okay, hope that helps; good luck!

Playground link to code

Upvotes: 1

Related Questions