打字稿界面初始化

Gia*_*bue 31 oop typescript

我的打字稿水平是'ABSOLUTE BEGINNER',但我有一个很好的OOP背景.我正在使用typescript来构建一个引用t.ds包含以下接口的外部库:

interface ISimpleObject {
    foo: string;
    bar?: any;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  3. 投下一个pojo:

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

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

我想这是一个相当微不足道的问题,我遗漏了一些关于打字稿的小事.

sdr*_*evk 59

Typescript2:

const simpleObject = {} as ISimpleObject;
Run Code Online (Sandbox Code Playgroud)

  • 这有效吗?一些ts-linting规则对此提出警告:“禁止在对象文字上进行类型断言,而应使用类型注释” (2认同)

Wir*_*rie 39

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

interface ISimpleObject {
    foo: string;
    bar?: any;
}
Run Code Online (Sandbox Code Playgroud)

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

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

function start(config: ISimpleObject):void {

}
Run Code Online (Sandbox Code Playgroud)

如果对象没有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"));
Run Code Online (Sandbox Code Playgroud)

只要签名不匹配,编译就会失败:

// compile fail
var bad = { foobar: 'bad' };
start( bad );

// compile fail
var bad: ISimpleObject = { foobar: 'bad' };

// and so on.
Run Code Online (Sandbox Code Playgroud)

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

var config: ISimpleObject = { foo: 'hello' };
Run Code Online (Sandbox Code Playgroud)

这样代码完成/ IntelliSense将在我使用config变量的任何地方工作:

config.bar = { extra: '2014' };
Run Code Online (Sandbox Code Playgroud)

TypeScript中没有"强制转换".它被称为类型断言,在这里描述的情况下不应该需要(我在上面包含了一个可以使用它的例子).没有必要声明变量Type,然后在这种情况下使用断言(因为类型已经知道).