简体   繁体   English

如何在 tsc 从 .js 文件生成的类型定义中包含继承的属性?

[英]How can you include inherited properties in type definitions generated from .js files by tsc?

I am trying to add typescript support to a vanilla javascript library via .d.ts files.我正在尝试通过 .d.ts 文件将 typescript 支持添加到vanilla javascript库。 I am trying to generate these type definition files with the "tsc" command, but I am running into many "property 'propertyName' does not exist on type 'typeName'" errors.我正在尝试使用“tsc”命令生成这些类型定义文件,但我遇到了许多“类型 'typeName' 上不存在属性'propertyName'”错误。

This is happening on lines that attempt to call a function on an instance of a child class when that function is defined only in the code for its parent class.当该函数仅在其父类的代码中定义时,尝试在子类的实例上调用函数的行上会发生这种情况。 It seems that while JSDoc is capable of inferring inherited functions by using "@extends" in the JSDoc comments of a child class, tsc is not.似乎虽然 JSDoc 能够通过在子类的 JSDoc 注释中使用“@extends”来推断继承的函数,但 tsc 不能。

For example:例如:

ParentClass.js父类.js

/**
* This is the parent class.
* 
* @class
*/
export class ParentClass {
  parentFunction(){
    console.log("Running parent function");
  }
}

childClass.js childClass.js

/**
* This is a child class.
* 
* @class
* @extends {ParentClass}
*/

import {ParentClass} from "./ParentClass";

class ChildClass extends ParentClass {
  // ChildClass vars and functions here
}

program.ts程序.ts

import {ChildClass} from "./ChildClass";

let cc = new ChildClass();
cc.parentFunction();

Upon attempting to compile the code, tsc will throw this error:尝试编译代码时,tsc 将抛出此错误:

error TS2339: Property 'parentFunction' does not exist on type 'ChildClass'.错误 TS2339:“ChildClass”类型上不存在属性“parentFunction”。

Is there any way to resolve this issue?有没有办法解决这个问题? If there is no way to make the typescript compiler recognize inherited properties, is there some way to make tsc ignore this issue so it can at least finish generating the type definition files and allow me to manually add the missing properties to the corresponding child class type definitions?如果没有办法让 typescript 编译器识别继承的属性,有没有办法让 tsc 忽略这个问题,所以它至少可以完成生成类型定义文件并允许我手动将缺少的属性添加到相应的子类类型定义?

You've forgotten to import the other files on the childClass.js and program.js .您忘记导入childClass.jsprogram.js上的其他文件。 It should be something like this:它应该是这样的:


ParentClass.js父类.js

/**
* This is the parent class.
*
* @class
*/
export class ParentClass {
  parentFunction(){
    console.log("Running parent function");
  }
}

childClass.js childClass.js

import { ParentClass } from './ParentClass'

/**
* This is a child class.
*
* @class
* @extends {ParentClass}
*/
export class ChildClass extends ParentClass {
  // ChildClass vars and functions here
}

program.js程序.js

import { ChildClass } from './childClass'

let cc = new ChildClass();
cc.parentFunction();

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

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