简体   繁体   English

Typescript声明文件包含没有成员实现的类定义

[英]Typescript declaration files contain class definitions with no member implementations

When I look at the Backbone declaration file I see this: 当我查看Backbone声明文件时,我看到:

export class Router extends Events {
    ...
    constructor (options?: RouterOptions);
    initialize (options?: RouterOptions);
    ...
}

and other places where a class has method definitions with no implementations. 以及其他类没有实现的方法定义的地方。 I thought this syntax was reserved for interfaces. 我认为这种语法是为接口保留的。 The compiler lets this pass in the declaration file but not in my own ts files. 编译器允许它传入声明文件,但不传入我自己的ts文件。

Is there a difference between the compilation rules for .d.ts vs .ts extensions? .d.ts.ts扩展的编译规则之间是否存在差异? If so, how should these types of classes be used differently from interfaces? 如果是这样,这些类的类应该如何以不同的方式使用?

.d.ts files are for describing an existing JavaScript or TypeScript implementation of some class. .d.ts文件用于描述某些类的现有 JavaScript或TypeScript实现。

A class in a .d.ts (I'll just call this a " declare class " since they are equivalent) is completely different from a virtual class or an interface. .d.ts一个类(我将它称为“ declare class ”,因为它们是等价的)与虚拟类或接口完全不同。 When you declare a declare class , you're saying "There is some other class that will be present that has this shape". 当你声明一个declare class ,你会说“还有一些其他类会出现这种形状”。 When you extend that class, the compiler is going to emit code on the assumption that there really will be a class (or sufficiently classlike thing) with that name present at runtime to use as the the next pointer in the prototype chain. 当您extend该类时,编译器将假定在运行时存在一个类(或类似于类似的东西)并且该名称在原型链中用作下一个指针时发出代码。

Just as an example, this code (by itself) does not work - you will get a runtime error because Foo isn't defined anywhere: 举个例子,这个代码(单独) 不起作用 - 你会得到一个运行时错误,因为Foo没有在任何地方定义:

declare class Foo {  public bar(): void; }
class FooDerived extends Foo { }

This code, on the other hand, is fine: 另一方面,这段代码很好:

interface Foo { bar(): void; }
class FooImpl implements Foo { public bar() {} }

If the file has a .d.ts extension, all of the classes are treated as if they were preceded by a declare keyword. 如果文件具有.d.ts扩展名,则所有类都被视为前面有一个declare关键字。 Declarations don't need an implementation, they just supply type information. 声明不需要实现,它们只提供类型信息。

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

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