David Armendariz
David Armendariz

Reputation: 1749

Specify object with at least one known property in Typescript

Is there any way in Typescript to specify an object that can have many properties but I know only one of them in advance?

For example:

const object = {a: 10, b: "hello"}

I only know for sure that a comes in this object, b can be another thing (like c) or maybe it is not present in the object. I would like to know if there is any way to specify a type where only a is known and other properties are "discarded".

Upvotes: 1

Views: 971

Answers (1)

S N Sakib
S N Sakib

Reputation: 1172

interface MyType {
  a: number;
 [key: string]: any;
}

const obj1: MyType = { a: 5 };
const obj2: MyType = { a: 5, b: 3 };
const obj3: MyType = { a: 5, c: 3 };

Upvotes: 3

Related Questions