首页 文章

组合类和接口类型

提问于
浏览
1

在Javascript(在WScript或HTA下),我会写下面的模式:

var fso = new ActiveXObject('Scripting.FileSystemObject');
var ext = fso.GetExtensionName('C:\test.txt');    //returns 'txt'
var badResult = fso.NonExistentMethod();          //raises a runtime error

使用TypeScript,我可以声明一个可以防止这种错误的接口:

module Scripting {
    export interface FileSystemObject {
        GetExtensionName(path: string): string,
        GetParentFolderName(path: string): string
    }
}

var fso: Scripting.FileSystemObject = new ActiveXObject('Scripting.FileSystemObject');
var ext = fso.GetExtensionName('C:\test.txt'); //ext is recognized as a string
//var badResult = fso.NonExistentMethod();     //will not compile

但是,我想像这样初始化 fso 变量:

var fso = new Scripting.FileSystemObject();

并让类型系统自动推断出 fso 的类型是接口 Scripting.FileSystemObject .

可以这样做吗?


1)我无法将构造函数添加到接口,因为接口只是对象的形状,而不是它的实现 .


2)我考虑创建一个内部接口,并使用类和构造函数扩展接口:

module Scripting {
    interface Internal {
        GetExtensionName(path: string): string;
        GetParentFolderName(path: string): string;
    }

    export class FileSystemObject extends Internal {
        constructor() {
            return new ActiveXObject('Scripting.FileSystemObject');
        }
    }
}

但是如果没有调用接口没有的基类型构造函数,则无法将构造函数添加到扩展类中 .


3)我不能有一个 declared 类,因为构造函数仍然是一个实现,不能写入 declared 类,这是一个环境上下文 .

1 回答

  • 3

    推断出fso的类型是接口Scripting.FileSystemObject . 可以这样做吗?

    当然 . 只要声明有一些东西,当 new 调用时将返回正确的类型 . 即 export var FileSystemObject: { new (): FileSystemObject };

    declare module Scripting {
        export interface FileSystemObject {
            GetExtensionName(path: string): string;
            GetParentFolderName(path: string): string;
        }
        export var FileSystemObject: { new (): FileSystemObject };
    }
    
    var fso: Scripting.FileSystemObject = new Scripting.FileSystemObject();
    var ext = fso.GetExtensionName('C:\test.txt'); //ext is recognized as a string
    var badResult = fso.NonExistentMethod();     //will not compile
    

    try it

    UPDATE 要自己实现这样的事情,你可以做到:

    module Scripting {
        export interface FileSystemObject {
            GetExtensionName(path: string): string;
            GetParentFolderName(path: string): string;
        }
        export var FileSystemObject: { new (): FileSystemObject } = <any>function(){
            return new ActiveXObject('Scripting.FileSystemObject');
        };
    }
    
    var fso: Scripting.FileSystemObject = new Scripting.FileSystemObject();
    var ext = fso.GetExtensionName('C:\test.txt'); //ext is recognized as a string
    var badResult = fso.NonExistentMethod();     //will not compile
    

相关问题