Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: why is a number assignable to a reference of type Object?

Why is this legal TypeScript?

var x: number = 5
var y: Object = x

Surely a number is not an Object. One might suspect that x is implicitly coerced (auto-boxed) to an object, but no:

if (!(y instanceof Object)) {
   console.log(typeof y)
}

prints

number

For the record:

$ tsc --version
Version 1.8.10
like image 334
Roly Avatar asked Sep 18 '16 20:09

Roly


People also ask

Is number an object in TypeScript?

TypeScript is like JavaScript which supports numerical values as Number objects. The numbers in typescript are used as both integers as well as floating-point values. The number class acts as wrapper and manipulates the numeric literals as they were objects.

How do I assign a number in TypeScript?

The Typescript also has the Number object. The Number object is created using the Number constructor i.e by using the new Number() keyword. You can check the type of a variable using the typeof keyword.

What is the difference between number and number in TypeScript?

If you use Number in a place where a type is expected, TypeScript will not complain, because Number is an interface. If you use Number in a place where a value (something that exists in emitted code) is expected, TypeScript will not complain, because Number is also a global constructor.

What type of value is number in TypeScript?

Number. As in JavaScript, all numbers in TypeScript are either floating point values or BigIntegers.


1 Answers

Type compatibility in TypeScript is based on structural subtyping, not nominal typing. That said, consider the two following interface definitions:

interface IFoo { X: number }
interface IBar { X: number; Y: number }

Does IBar extend IFoo? No.

But is IFoo compatible with IBar? Yes.

The members of IFoo are a subset of IBar members, thus you can assign any IBar to IFoo. But it doesn't work the other way around:

var x: IFoo;
var y: IBar;

x = y // all good
y = x // type error, x has no Y member

This way in Typescript all types are compatible with Object if you think of it as the empty interface. This way you can pass any valid typescript value to functions accepting Object and play well with the way Javascript libs are written.

I suggest reading Type Compatibility in docs and the last paragraph about Subtype vs Assignment.

like image 102
krontogiannis Avatar answered Oct 09 '22 04:10

krontogiannis