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

Generic conditional type X extends any ? X : X does not allow generic assignment of X #37272

Closed
eibens opened this issue Mar 7, 2020 · 1 comment

Comments

@eibens
Copy link

eibens commented Mar 7, 2020

TypeScript Version: Nightly

Search Terms:
generic, conditional type, cannot be assigned, generic return value

Expected behavior:
A value of type X is a valid return value for a function returning Always<X>, since the latter is a generic conditional type that always evaluates to X.

Actual behavior:
Does not compile. Error message:
Type 'X' is not assignable to type 'Always<X>'. (2322)

Related Issues:
#31751 seems to be more about never type semantics.

Code
You can substitute any type for any in the definition below and it will fail regardless.

export type Always<X> = X extends any ? X : X
const f = <X>(): Always<X> => /*error*/ null as unknown as X /*error*/
Output
const f = () => null;
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "useDefineForClassFields": false,
    "alwaysStrict": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "downlevelIteration": false,
    "noEmitHelpers": false,
    "noLib": false,
    "noStrictGenericChecks": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "esModuleInterop": true,
    "preserveConstEnums": false,
    "removeComments": false,
    "skipLibCheck": false,
    "checkJs": false,
    "allowJs": false,
    "declaration": true,
    "experimentalDecorators": false,
    "emitDecoratorMetadata": false,
    "target": "ES2017",
    "module": "ESNext"
  }
}

Playground Link: Provided

@eibens eibens changed the title Generic conditional type X extends any ? X : X does not allow generic assignment of X? Generic conditional type X extends any ? X : X does not allow generic assignment of X Mar 7, 2020
@eibens
Copy link
Author

eibens commented Mar 8, 2020

#37279 is actually extremely similar and describes how I encountered this problem in the first place. I guess since X may also be a type union it is working as intended. Same solution applies:

export type Always<X> = [X] extends [any] ? X : X
const f = <X>(): Always<X> => null as unknown as X

@eibens eibens closed this as completed Mar 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant