0

Reproducible code:

class MyObject{
    id: number|null = null
}

const a = new MyObject()
console.log(typeof a.id)

'object'

Is there a way to get the 'number' type from that property?

Edit:

I understand why typeof null is object. But my question is: is there a way (maybe reflection or something) to get that number|null complete type.

E. Williams
  • 405
  • 1
  • 6
  • 21
  • 1
    `typeof null` is `"object"` for historical reasons. [Why is typeof null "object"?](https://stackoverflow.com/q/18808226) – VLAZ Dec 07 '22 at 08:53
  • Does this answer your question? [Why is typeof null "object"?](https://stackoverflow.com/questions/18808226/why-is-typeof-null-object) – Matthieu Riegler Dec 07 '22 at 08:57
  • More importantly, this might be [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). [The type information is only available at compiletime](https://github.com/Microsoft/TypeScript/wiki/FAQ#what-is-type-erasure). At runtime there is no knowledge of what a variable or property *might* be. Just what the current value it is. For example `foo: string|number = 1` will never reveal it might have a string at runtime. – VLAZ Dec 07 '22 at 08:59
  • `typeof` does not return the ‘compile’ time type, only the runtime type. – user3840170 Dec 07 '22 at 09:14
  • and is there another approach to get the compile time type?. I mean in other languages when I declare an optional type for a property Optional I can get the full Optional type. – E. Williams Dec 07 '22 at 09:14
  • There is no way to get the `number` type from `id` at runtime, unless you make sure to always assign a number to it. – Tobias S. Dec 07 '22 at 09:16

1 Answers1

1

If you want to get the type number of your new object, you need to assign a value to it.

Johan
  • 2,088
  • 2
  • 9
  • 37