Typescript接口初始化



我的打字水平是'绝对初学者',但我有很好的OOP背景。我正在构建一个引用包含以下接口的外部t.ds库的typescript:

interface ISimpleObject {
    foo: string;
    bar?: any;
}

现在,如果我想调用一个有IRequestConfig参数的方法,我如何创建一个?我可以看到不同的选项:

    创建一个简单的ISimpleObject实现。我不喜欢这种方法,因为它看起来像样板代码
  1. 不要初始化对象(我担心这会破坏某些东西…):

    var x :IsimpleObject; x.bar = 'xxx'; callMethod(x);

  2. 转换pojo:

    var x :IsimpleObject = <IsimpleObject>{foo: 'yyy', bar:'xxx'};

    我也不喜欢这种方法,因为它不强制类型安全…

我想这是一个相当琐碎的问题,我错过了一些关于打字的琐碎的东西。

Typescript2:

const simpleObject = {} as ISimpleObject;

如果你有一个这样的界面:

interface ISimpleObject {
    foo: string;
    bar?: any;
}

此接口仅在编译时用于代码提示/智能感知。接口用于提供一种严格且类型安全的方式,以一致的方式使用具有已定义签名的对象。

如果您有一个使用上面定义的interface的函数:

function start(config: ISimpleObject):void {
}

如果一个对象没有ISimpleObject接口的精确签名,TypeScript编译就会失败。

调用函数start有多种有效的技术:

// matches the interface as there is a foo property
start({foo: 'hello'});
// Type assertion -- intellisense will "know" that this is an ISimpleObject
// but it's not necessary as shown above to assert the type
var x = <ISimpleObject> { foo: 'hello' }; 
start(x);
// the type was inferred by declaration of variable type
var x : ISimpleObject = { foo: 'hello' };  
start(x);
// the signature matches ... intellisense won't treat the variable x
// as anything but an object with a property of foo. 
var x = { foo: 'hello' };
start(x);    
// and a class option:
class Simple implements ISimpleObject {
    constructor (public foo: string, public bar?: any) {
       // automatically creates properties for foo and bar
    }
}
start(new Simple("hello"));

任何时候签名不匹配,编译将失败:

// compile fail
var bad = { foobar: 'bad' };
start( bad );
// compile fail
var bad: ISimpleObject = { foobar: 'bad' };
// and so on.

没有"正确"的方法去做。这是一个风格选择的问题。如果它是一个被构造的对象(而不是直接作为参数传递),我通常会声明类型:

var config: ISimpleObject = { foo: 'hello' };

这样代码完成/智能感知将工作在任何地方我使用config变量:

config.bar = { extra: '2014' };
在TypeScript中没有"强制类型转换"。它被称为类型断言,在这里描述的情况下不应该需要它(我在上面包含了一个可以使用它的示例)。在这种情况下,不需要声明变量Type然后使用断言(因为类型已经已知)。
  • 你不能创建一个接口的实例,因为Typescript不会把它"翻译"成js。你可以检查创建的js,你会发现里面什么都没有。对于编译错误、类型安全和智能感知来说,这很简单。

    interface IStackOverFlow
    {
       prop1 : string;
       prop2 : number;
    }
    public MyFunc(obj : IStackOverFlow)
    {
        // do stuff
    }
    var obj = {prop1: 'str', prop2: 3};
    MyFunc(obj); // ok
    var obj2 = {prop1: 'str'};
    MyFunc(obj); // error, you are missing prop2
    // getObj returns a "any" type but you can cast it to IStackOverFlow. 
    // This is just an example.
    var obj = <IStackOverFlow> getObj();
    

最新更新