Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
frankpf opened this issue Aug 23, 2018 · 1 comment
Closed
Labels
Duplicate An existing issue was already created

Comments

@frankpf
Copy link

frankpf commented Aug 23, 2018

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

@ahejlsberg
Copy link
Member

Duplicate of #11152.

@ahejlsberg ahejlsberg added the Duplicate An existing issue was already created label Aug 23, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants