简体   繁体   English

Typescript:为什么此代码是100%有效的javascript代码时会引发异常

[英]Typescript: why this code throws an exception while it is a 100% valid javascript code

It is claimed that TypeScript is a superset of Javascript. 据称TypeScript是Javascript的超集。 Here's a question on Stack about this. 这是关于Stack的一个问题 Here's a quote from spec: 这是spec的报价:

TypeScript is a syntactic sugar for JavaScript. TypeScript是JavaScript的语法糖。 TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. TypeScript语法是ECMAScript 2015(ES2015)语法的超集。 Every JavaScript program is also a TypeScript program. 每个JavaScript程序也是TypeScript程序。

So my understanding is that any stand-alone javascript file can be treated as a valid typescript code, ie compiled (may be with some additional flags) by tsc compiler. 因此,我的理解是,任何独立的javascript文件都可以视为有效的打字稿代码,即由tsc编译器进行编译(可能带有一些其他标志)。

But here's an example of js code: 但是这是一个js代码示例:

class ClassA {}
ClassA.prototype.ping = () => {console.log('PING')}

That is valid javascript but if you'll try to compile it with typescript, you'll get: error TS2339: Property 'ping' does not exist on type 'ClassA' 那是有效的javascript,但如果尝试使用error TS2339: Property 'ping' does not exist on type 'ClassA'进行编译,则会得到: error TS2339: Property 'ping' does not exist on type 'ClassA'

One can declare interface which ClassA can implement, also, it's highly untypical to write code like this (combine class and prototype syntaxes) but nevertheless - this looks like an example of valid js code which raises an error while compiling with tsc. 可以声明ClassA可以实现的接口,而且,编写这样的代码(组合类和原型语法)是非常不典型的,但是尽管如此-这看起来像是一个有效的js代码示例,在使用tsc进行编译时会引发错误。

So the question is - how this does not contradict to the quote from spec? 因此,问题是-这与规范中的报价如何矛盾?

TypeScript is a syntactic superset of JavaScript that doesn't change JavaScript's runtime behavior. TypeScript是JavaScript的语法超集,不会更改JavaScript的运行时行为。 So any expression or statement or declaration you write in JavaScript is syntactically legal TypeScript. 因此,您用JavaScript编写的任何表达式,语句或声明在语法上都是合法的TypeScript。

This doesn't mean that all JS code is considered to be warning-free TypeScript. 这并不意味着所有JS代码都被视为无警告TypeScript。 After all, a major goal of TypeScript is to identify bad constructs like 毕竟,TypeScript的主要目标是识别不良构造,例如

var s = "hello world" * 423;
var t = "qzz".subtr(2);
var u = [1, 2, 3] + 5;
var w = window.navgtator;

These are all "valid" JavaScript expressions, they just happen to have undesirable runtime behavior that people don't want to actually do. 这些都是“有效的” JavaScript表达式,它们恰好具有人们不希望实际执行的不良运行时行为。

As usual in TypeScript, you can tell the type system about extra information 像在TypeScript中一样,您可以将其他信息告知类型系统

class ClassA {}
// Declare additional method
interface ClassA { ping(): void; }
// OK
ClassA.prototype.ping = () => {console.log('PING')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM