Home > OS >  Need help on Generic extend string purpose
Need help on Generic extend string purpose

Time:08-27

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

    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

CodePudding user response:

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.

  • Related