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

index signature and typed key in TS?

The following code will always produce an error, but as a sketch, this is what I aim to represent:

interface A  {
    [ key : string ] : string, 
    "anotherKey" : MyInterface
}

I’ve checked a few books, TS documentation, tested in ts-node, but I am not that well versed and need some help.

How can I specify an object whose most keys are "key":"value" but some specific aren’t?

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 :

Use a regular type and intersection:

type MySpecialType = {
    specific: { type: number; };
    extremely: { specific: { type: string; } };
} & {
    [key: string]: string;
};

& is read as and

So this is saying this is a really specific type and an index signature of strings to strings.

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