Skip to content

[6.x] Getting'unassingable to type' when returning value from method that needs to infer generic from parameters #63461

@spaceemotion

Description

@spaceemotion

🔎 Search Terms

is unassingable to type return value generic, unassingable to type return value

🕗 Version & Regression Information

  • This changed between versions 5.9.3 and 6.0.3

⏯ Playground Link

https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true&useDefineForClassFields=true&noUnusedLocals=true&noUnusedParameters=true&target=99&isolatedModules=true&verbatimModuleSyntax=true&isolatedDeclarations=false&strictBuiltinIteratorReturn=true&allowImportingTsExtensions=true&noUncheckedSideEffectImports=true&ts=6.0.3#code/C4TwDgpgBAMghgIwgGygXigbysCAPYALigGdgAnASwDsBzAGigGMB7ZF84squqAXwBQA0JCgBhOGUTIIAFXDQ0AqFAA+pCjVrK1sRCh0BuISOgAlAK7VglALYQAClVuUbAN0U713LV6hmIVnIAEwAeJxZIclAAaQgQRisAa2oWAHdqAD4jEwV-Kxt7GEoyUNl0fOs7R2dXSg9MitkAbQBdXNEAOTh7ADEOeUgyqHxcamCScUlgaTkFRqUVctGIccmfOh0VAH4oAHIN2j2tqGJlglWJvSRkE5395H1kY5VX06hqCA9yIWDAx-I0FY1DIUFscDAshYxDKvXILFsIwuaymUgQMkGEEYsihSLGVwkaIx8wAFDpkCUiFBZHCEW16DpgNCoN0+gMFGUoZkGQBKdCNSxVIqUzksTLGAQAMysTBsLGoUEB4LAJJ5xEFhQgxVBmB0wNBuAIJC4mjobQqbWMKh0AHobVAAOocJLG2325VQ0KHRjwG6ZEmG4AkRh7R43PY8iUqO1QAAiLAgk1SwCgaWdhB0gOAFnICo9LADo2DDyeEeMgiAA

💻 Code

type Label = { text: string, color: string }

type CastableType =
  | string
  | Label
  ;

type RuntimePrimitive =
  | string
  | Record<PropertyKey, unknown>
  ;

type RuntimeList<T = RuntimePrimitive> = T[]

type NameForType<T extends CastableType> =
  T extends string
    ? 'string'
    : T extends Label
      ? 'label'
      : never

declare const mapTo: <TFrom extends CastableType, TTo extends CastableType>(
  list: TFrom[],
  to: NameForType<TTo>,
) => RuntimeList<TTo>;

function remap(): RuntimeList {
  const texts: string[] = [];
  
  // Works:
  // mapTo<string, Label>(texts, 'label');

  // Does not work:
  return mapTo(texts, 'label');
}

🙁 Actual behavior

The 'label' string is marked as unassignable, and i need to add generics to the mapTo call to help it infer the correct types.

Here's an image from production code (TS 6):

Image

🙂 Expected behavior

No error, everything can be inferred just fine.

Here's an image from production code (TS 5):

Image

Additional information about the issue

To me, this seems to be an interplay between the return value trying to pre-filter the accepted arguments? However, there should be no issue as the RuntimePrimitive kind of works as a generic fallback.

The error also goes away as soon as the return is removed, or the return value is first assigned to a variable, before returning it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions