Skip to content

Use keyof to get the union name in generic comprehensions. If the key value contains an ordinary function, the type hint is lostΒ #55124

@biggerstar

Description

@biggerstar

πŸ•— Version

  • ts version: 5.1.6
  • webStorm version 2022.3.1
  • os version mac 13.4.1

⏯ Playground Link

Playground Link

πŸ’» Code

type Values<T> = T[keyof T];
type ExtractFields<Options> = Values<{ // Extract the names of all second level keys passed in to the options object
  [K in keyof Options]: Options[K] extends object ? keyof Options[K] : never
}>
type SetType<Options> = {
  [key: string]: any
  target?: ExtractFields<Options>
}

function test<OptionsData extends SetType<OptionsData>>(options: OptionsData): void {
  console.log(options);
}

// result: "$test3" | "$test4" | "$test1" | "$test2"
type SuccessExtractField = ExtractFields<{  // Successfully extracted all key names,
  data1: {
    $test1: 111,
    $test2: null,
  },
  data2: {
    $test3: {},
    $test4: () => {},
  }
}>  

// On webStorm, the test function will report a red alert indicating a type mismatch.
// If the target type is set to string, it will not report a red alert, but this does not meet our expectations
test({
  target: '$test4',  // Expect normal code here to prompt $testX
  data1: {
    $test1: 111,
    $test2: null,
  },
  data2: {
    $test3: {},
    $test4: () => {},
 // $test5(){}  // Add $test5 and an error will be reported in target.
  }
})

πŸ™ Actual behavior

At present, there are two problems. The second question seems to be a bug

  1. The webStorm editor reports red after writing the relevant code, but can be sure that the code will not report an error if it is normal under intuitive circumstances.
  2. Type derivation failed. When using ExtractFields alone to extract the key names of all second layers of an object, the following situations occur. Matching key value pairs without a function is normal
    {$test4: ()=>{}} ------ Target can correctly code prompt
    {$test5() {}} ------ Target cannot correctly code prompt

πŸ™‚ Expected behavior

Correct code hints in the editor

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions