MD10
MD10

Reputation: 1531

How to Enforce field to be in object typescript

I have to create a type that has one required property and the rest can be anything. For example I want to have all objects that have _id: string

{_id: "123"} // will work
{a: 1} // wont work because doesnt have _id field 
{_id:"sadad", a:1} // will work

How can I do it with typesccript?

Upvotes: 0

Views: 429

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

Explicitly inform the type there is a key with _id and after that, it can be any object key-value pair Record<string, unknown>

type ObjectType = { _id: string } & Record<string, unknown>;

const a: ObjectType = { _id: "123" }; // will work
const b: ObjectType = { a: 1 }; // Property '_id' is missing in type
const c: ObjectType = { _id: "sadad", a: 1 }; // will work

P.S. Reference for RecordKey

What is the Record type in typescript?

Upvotes: 2

Related Questions