Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

primitive - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...