Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can I not have a generic interface WITH an optional property of a known type?

interface Thing {
  [ index: string ]: string | number | boolean | Thing | Array<string | number | boolean>
}

interface FooBarable extends Omit<Thing, 'foo' | 'bar'> {
  foo: string;
  bar?: string;
}

const x: FooBarable = { abc: 123, bool: true, foo: 'abc' };

gives me:

Property 'bar' of type 'string | undefined' is not assignable to 'string' index type 'string | number | boolean | Thing | (string | number | boolean)[]'.

Playground

Is there a way to make this work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try using a type intersection rather than inheritance.

interface Thing {
  [ index: string ]: string | number | boolean | Thing | Array<string | number | boolean>
}

type FooBarable = Thing & {
  foo: string;
  bar?: string;
}

const x: FooBarable = { abc: 123, bool: true, foo: 'abc' };

console.log(x);

Playground link

This is subtle, because type and interface are mostly the same, and interfaces are usually preferred, but this is one case where a type intersection is closer to what you want. (I believe that’s a similar issue to what’s described here.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading