johnnyshrewd
johnnyshrewd

Reputation: 1180

Can you have a Typescript Interface with only some known values?

I have an object that is dynamic and I know that it will always have certain properties, but it will also have some others.

{
   id: number,
   name: string,
   ... // some dynamic stuff
}

Is there a way to express this so that the object can still get IntelliSense on the known properties but be ok with having some other stuff.

I'm quite new to Typescript so sry if this is a noob question.

Upvotes: 0

Views: 601

Answers (1)

Sergeon
Sergeon

Reputation: 6788

As per @jcalz suggests, the best I know for this is an index signature:

interface Foo {
  id: number;
  name: string;
  [prop: string]: any;
}

This will allow to add anything to an object that has id and number, and it will comply with the Foo interface:

const f: Foo =  {
  id: 1,
  name: 'bar',
  zoo: 'keeper',
  something: new Map<string, symbol>(),
}; // no compile errors here

And you can also add properties later:

foo.anything = 'value';

However, tsc will still request for id and name. The following declaration:

const f: Foo =  {
  id: 1,
  zoo: 'keeper',
  something: new Map<string, symbol>(),
}

Will produce:

Type '{ id: number; zoo: string; something: Map; }' is not assignable to type 'Foo'. Property 'name' is missing in type '{ id: number; zoo: string; something: Map; }'


In cases where you don't know how many props you will be add, but you happen to know the common type of all of them, you can narrow a bit more:

interface Poem {
  author: Author,
  language: string,
  [verses: string]: string;
}

Upvotes: 3

Related Questions