【发布时间】:2020-08-13 09:20:53
【问题描述】:
我正在迈出将一个相当大的项目从 javascript 迁移到 typescript 的第一步。作为一名大约 2 年前开始 javascript 开发的 Java 开发人员,我的工具链仍处于初级阶段。
我正在尝试将一个小的 JS 文件迁移到 TS 作为概念证明。 JS代码配置了Basic Primitives Diagram。
几乎所有事情都解决了。但是我在以打字稿可以理解的方式声明全局范围函数时遇到了大问题。这是我的一小部分代码:
export {}
declare global {
export interface Window {
MyGlobalVar: any;
}
export ChartItemConfig{
//properties
}
//I thought this and the following declarations would solve the problem. They dont :(
export interface primitives {
orgdiagram: Orgdiagram;
}
export interface Orgdiagram {
Config: Config;
}
export interface Config {
//properties
}
}
window.MyGlobalVar.myGlobalFunction = function (id: string, items: Array<ChartItemConfig>) {
//... more code
// @ts-ignore
let options: Config = new primitives.orgdiagram.Config();
//... more code
}
我想摆脱@ts-ignore 声明。但无论我尝试什么,我的代码都不会转换。我收到错误TS2693: 'primitives' only refers to a type, but is being used as a value here.
我确定这是一个初学者的问题,但我在www中找不到解决方案。
编辑:
我似乎对我的问题不够清楚:new primitives.orgdiagram.Config(); 在运行时是有效的 JS 代码。如何以 TS 理解为构造函数调用的方式声明符号?
编辑:
我的当前版本:
export {}
declare global {
export interface Window {
MyGlobalVar: any;
}
export const primitives:Primitives;
export class Primitives {
orgdiagram: Orgdiagram;
}
export class Orgdiagram {
Config: () => Config;
}
export class Config { }
//... more
}
window.MyGlobalVar.myGlobalFunction = function (id: string, items: Array<ChartItemConfig>) {
//The following line fails with: TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type
let options: Config = new primitives.orgdiagram.Config();
//... more
}
编辑:
我终于让它工作了。 fettblog.eu introduced me to the constructor interface pattern,解决了我的问题:)
我的工作声明现在是
export {}
declare global {
const primitives:Primitives;
class Primitives {
orgdiagram: Orgdiagram;
}
class Orgdiagram {
Config: ConfigConstructor;
}
interface ConfigConstructor{
new (): Config;
}
class Config {
//....
【问题讨论】:
-
我认为您误解了接口的用途,它们等同于类型/类,但您可以创建一个必须符合接口属性的对象,也就是
export interface Person { name: string } const myPerson: Person = { name 'Mike' }跨度> -
接口本身在运行时并不存在,它只存在于 ts-compiler 中。
标签: javascript typescript