1

Depending on the type of parameter paramNameOrId, the output type should switch between IdLabel and NameLabel. The following code block below works also as expected.

Main Code Block:

type IdLabel = { id: number };
type NameLabel = { name: string };

type NameOrIdType<T extends number | string> = T extends number
  ? IdLabel
  : NameLabel;

function createLabel<T extends number | string>(
  paramNameOrId: T,
): NameOrIdType<T> {
  const nameOrId =
    typeof paramNameOrId === 'string'
      ? { name: paramNameOrId }
      : { id: paramNameOrId };
  return nameOrId;
}

let a = createLabel('typescript'); // { name: 'typescript' }
let b = createLabel(4.1); // { id: 4.1 }

Problem:

Only the TypeSystem of TypeScript screams and means:

Type  { name: T & string; id?: undefined; } OR 
      { id: T; name?: undefined; }  
is not assignable to type 'NameOrIdType<T>'.


Type  { name: T & string; id?: undefined; } 
is not assignable to type 'NameOrIdType<T>'.ts(2322)

What is my mistake? What would be the proper implementation in this case?

  • See [the question this duplicates](https://stackoverflow.com/questions/59904247/implementing-a-generic-function-with-a-conditional-return-type). Translating the [answer](https://stackoverflow.com/a/59905652/2887218) there to your example code leads to [this](https://tsplay.dev/Nr23VN). – jcalz Apr 03 '21 at 17:31
  • Someone made it their life's work to close my questions as duplicate. A conspiracy? When they realize that it is not a duplicate, it is so late that no one can answer it anymore, same here: https://stackoverflow.com/questions/64805354/how-to-find-singular-in-the-plural-when-some-letters-change-what-is-the-best-ap –  Apr 03 '21 at 17:35
  • Please consider reading the other question and its answer(s). If your issue is not resolved after that, come back here and edit the question so that it clearly explains how the other question/answers is not applicable, and I'd be happy to vote to reopen. Good luck! – jcalz Apr 03 '21 at 17:38
  • 1
    I've found the solution; meanwhile, it is new, it is newer as the former answers claiming, it would not be possible. Thanks to you, people won't find out how. :/ It's getting really nasty here, really! –  Apr 03 '21 at 17:53
  • I assure you I am not trying to do any such thing, and I would certainly appreciate civility and a default assumption of good faith from all parties. If your new solution is better than the other ones, then you should post it in the existing question; activity on an older question causes it to jump to the top of the [active queue](https://stackoverflow.com/questions/tagged/typescript?tab=Active), so people will see it. If you think this question is not a duplicate, then you should really articulate how via a question edit. Good luck again. – jcalz Apr 03 '21 at 17:55
  • 1
    Open the question, I'll post the answer,.. –  Apr 03 '21 at 17:55

0 Answers0