Skip to content

String literal types aren't inferred from object literals when using generics #26621

Closed
@frankpf

Description

@frankpf

TypeScript Version: 3.0.1

Search Terms: "Type string is not assignable to type", narrow types, object literal, string literal

Code

declare function f<T>(arg:  T ): void

f({ someKey: 'C' }) // someKey's type is (incorrectly) inferred as 'C'
f<{someKey: 'C'}>({ someKey: 'C' }) // someKey's type is (correctly) inferred as 'C'

Expected behavior:
In the first function call, someKey's type should be 'C'.

Actual behavior:
someKey' s type is inferred as string. I don't know if this is a bug or a feature request, but when not using generics, this does not happen (see this playground link). This is especially problematic when using discriminated unions. Here's the actual code that prompted me to open this issue:

import {Option, some, none} from 'fp-ts/lib/Option'

type Player = 'black' | 'white'

type WinCondition =
    | { type: 'win', player: Player }
    | { type: 'draw' }```

const checkWin = (someArg: number): Option<WinCondition> => {
    return some({ type: 'draw' })
  // ^-- Type '{ type: string; }' is not assignable to type '{ type: "draw"; }'
}

Playground Link: https://www.typescriptlang.org/play/#src=declare%20function%20f%3CT%3E(arg%3A%20%20T%20)%3A%20void%0D%0A%0D%0Af(%7B%20someKey%3A%20'C'%20%7D)%0D%0Af%3C%7BsomeKey%3A%20'C'%7D%3E(%7B%20someKey%3A%20'C'%20%7D)%0D%0A

Related Issues: #26413

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