Reputation: 45
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
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!
Upvotes: 1