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

How to make generics more specific?

There is a function

function createStats<K extends string[]>(arr: K): Stats<K[number]>

and when I do this for example

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

const testStats = createStats(["maxHealth"])

testStats is Stats<string> and I want it to be Stats<"maxHealth">

The only way I know how to fix it is to add as const. But I don’t want to write as const through out all of my code, so it isn’t really a good solution for me.

>Solution :

You can use a generic const-type parameter also known as const-modifier. Similar to a const-assertion TypeScript will try to infer the most specific type of a generic argument.

declare function createStats<const K extends readonly string[]>(
  arr: K,
): Stats<K[number]>;
createStats(["maxHealth"]);
//^? createStats<readonly ["maxHealth"]>(arr: readonly ["maxHealth"]): "maxHealth"

TypeScript Playground

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