tc39 / proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
https://tc39.es/proposal-type-annotations/
4.27k stars 47 forks source link

Notation of types #160

Closed w3nl closed 2 years ago

w3nl commented 2 years ago

Why not use the the object names from JavaScript, like:

function equals(x: Number, y: Number): Boolean {
    return x === y;
}

The standard "types" like Number, String, Boolean, etc are already interfaces to the value.

const x = 42; // or const x = new Number(42);
x.constructor === Number; // true
x.constructor.name === 'Number'; // true

When we use lowercase, it's a new naming convention.

climba03003 commented 2 years ago

I believe Number means to be the Number constructor. It will be easily to mess up the typing with built-in constructor.

nikeee commented 2 years ago

JS uses lower-cased names for the primitive types. The ones with the upper case letter are their primitive wrapper object.

Therefore, typeof returns the lower-cased version.

typeof 42 // "number"
spenserblack commented 2 years ago

While the TypeScript-style types are often used (e.g. ident: number) in this proposal's examples, the basic idea right now seems to be that anything after : until either the , preceding the next parameter or the end of the parameters list ()) would be valid. https://github.com/tc39/proposal-type-annotations/blob/a4315be8a311980ca525dc539585b10b7478a63e/syntax/grammar-ideas.md#annotation-type-delimiters-and-allowed-types

So, per this proposal, you could use ident: Number if you wanted, but, for example, you probably wouldn't want to do that if you were also going to use TypeScript to compile that code.

There could in the future be a tool that does use the wrapper types for type annotations, but I think this proposal is basically attempting to define a way that code from all these tools that use type annotations could be executed with a JavaScript engine, without needing those tools.

w3nl commented 2 years ago

@climba03003 yes it is the built-in constructor, so you know it's the same type. I think it's very usefull, and easy for tools to check if it's the same "type".

@spenserblack Thanks!

@nikeee

typeof 42 // "number"

I personnaly don't like that typeof returns lowercase, and return object for "all other types" like arrays.

Type Result
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol "symbol"
Function "function"
Any other object "object"

Why do we not keep the original naming in the typeof method?

For this reason i always use contructor checks to check the type of a value, and never use typeof anymore.