4

I have a TypeScript question when I wrote TS conditional types, like following code:

type T = 1 extends {} ? true : false;

Why T returns true?

adiga
  • 34,372
  • 9
  • 61
  • 83
ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • 9
    `Number` extends `Object` – Samathingamajig Apr 08 '22 at 14:45
  • 2
    and any primitive type (number, string, boolean) has a corresponding Class (Number, String, Boolean). The type of a var like that gets converted by the engine according to the operation you need to do and it's often made with a so called transient object that gets destroyed after the operation is done. So even if the literal `1` is supposed to be `number`, it gets threated as `Number` in that case. – Diego D Apr 08 '22 at 14:50
  • 1
    Hmm, you're changing the scope of your question after you've asked it. Has it stabilized yet? – jcalz Apr 08 '22 at 15:01
  • 1
    I've reverted the question to its original form. You can ask about the second part in a different question. It's unfair to the comments and the answer. – adiga Apr 08 '22 at 15:05
  • The type `{}` means "anything which can be indexed into like an object" and, as such, only prohibits `null` and `undefined` (assuming `--strictNullChecks`). You could write `(1).toFixed` so `1` is indexable. – jcalz Apr 08 '22 at 15:09
  • 1
    Related: [Difference between 'object' ,{} and Object in TypeScript](https://stackoverflow.com/questions/49464634/difference-between-object-and-object-in-typescript) – Felix Kling Apr 08 '22 at 15:16
  • @DiegoDeVita: Not *every* primitive type, only the ones you mentioned and bigint (not undefined, null or symbols). – Felix Kling Apr 08 '22 at 15:17
  • @FelixKling why not symbols? – jcalz Apr 08 '22 at 15:25
  • 2
    [Here is the OP's new/related question](https://stackoverflow.com/questions/71799555/why-1-extends-key-string-never-is-false), for those who wanted to weigh in. – Alexander Nied Apr 08 '22 at 15:26
  • @FelixKling ok I went too far after reading again yesterday some pages from Javascript: the definitive guide (6th edition if I'm not mistaken) ... and it's quite old now ;) – Diego D Apr 08 '22 at 15:26
  • 1
    @jcalz: Seems like I was wrong about symbols! They do have an object wrapper. Somehow I thought they didn't but of course it must somehow be possible to access their description... I got carried away :D – Felix Kling Apr 08 '22 at 15:30

1 Answers1

1

Because <number> extends <Object> evaluates to true.