Repository navigation
Closed
Description
TypeScript Version: 3.2.2
Search Terms: string literal type infer
Code
type MethodNamesFrom<T> = {
[K in keyof T]: T[K] extends Function ? K : never
}[keyof T]
const obj = {
a: () => { },
b: () => { },
c: 2
}
// CASE 1: PROBLEM?
function Infer1<TObject, TKey extends MethodNamesFrom<TObject>>(o: TObject, k: TKey) {
}
Infer1(obj, 'a') // TKey infer "a" | "b"
// CASE 2: OK
function Infer2<TKey extends MethodNamesFrom<typeof obj>>(k: TKey) {
}
Infer2('a') // TKey infer "a"
// CASE 3: OK, explicity define generic types
Infer1<typeof obj, 'a'>(obj, 'a') // TKey infer "a"
// CASE 4: OK, explicity define "a" as "a"
Infer1(obj, 'a' as 'a') // TKey infer "a"
// CASE 5: OK, enforces string in TKey
function Infer3<TObject, TKey extends string & MethodNamesFrom<TObject>>(o: TObject, k: TKey) {
}
Infer3(obj, 'a') // TKey infer "a"Expected behavior: Infer TKey as "a" | "b" in case 1
Actual behavior: Should infer TKey as "a"
Related Issues:
Reacted by Erik Weilow
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScript
Activity
eweilow commentedon Jan 12, 2019
Further context: https://twitter.com/gt_katakura/status/1083744926226100225
gtkatakura commentedon Nov 12, 2021
Just to notify here that at least versions 3.3.3+ doesn't have more this bug. I think this issue can be closed.
jakebailey commentedon Jul 9, 2023
This was fixed in #29478, yes.