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

Need help on Generic extend string purpose

Hi need help to understand following typescript

  1. Generic K extends string

  2. If K is restricted to string type then how can we iterate using key in K

    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

    type NewMappedTypes<K extends string> = { [key in K]: boolean } // 1
    //2. if Generic is restricted to string type then how can we iterate over keys
    function composeTypedMap<K extends string>(k: NewMappedTypes<K>) {
        return k;
    }
    
    const t = composeTypedMap({ 'a': true ,'b':false});
    console.log(t)
    

PlaygroundLink

>Solution :

K extends string is a generic constraint. You’re right in thinking that K must be assignable to string.

However (while the syntax doesn’t make it obvious) it doesn’t mean just "one" string can be used for K: you can supply a union of string literal types, which will be used in the type mapping operation of that type utility.

Here’s another example to help clarify what’s happening:

TS Playground

// Maps the members (constituents) of the string union to keys in the object:
type StringUnionToKeysInObjectOfBooleanValues<U extends string> = {
  [Str in U]: boolean;
};

type ExampleStringLiterals = 'foo' | 'bar' | 'baz';

type ExampleObject = StringUnionToKeysInObjectOfBooleanValues<ExampleStringLiterals>;
   //^? Looks like:
/*

type ExampleObject = {
    foo: boolean;
    bar: boolean;
    baz: boolean;
}

*/

type ObjectFromJustString = StringUnionToKeysInObjectOfBooleanValues<string>;
   //^? Looks like:
/*

type ObjectFromJustString = {
    [x: string]: boolean;
}

*/


In the code you’ve shown, the compiler is using type inference to infer the types of the keys in the object literal that you provide as the argument to the function:

{ 'a': true ,'b':false}

They are inferred as the string union "a" | "b" and become the actual type used in place of the generic type parameter K.

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