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

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

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

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

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

  3. 演员pojo:

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

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

我想这是一个相当琐碎的问题,我遗漏了关于typescript的一些琐碎之处.

推荐答案

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

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.

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

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

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

config.bar = { extra: '2014' };

打字脚本中没有"铸造".它被称为类型断言,在这里描述的情况下不应该需要它(我在上面提供了一个可以使用它的示例).在本例中,不需要声明变量类型,然后使用断言(因为类型已经已知).

Typescript相关问答推荐

为什么TypScript对条件函数类型和仅具有条件返回类型的相同函数类型的处理方式不同?

类型缩小对(几乎)受歧视的unions 不起作用

定义JMX的类型:类型上不存在属性键

如何使用TypScript和react-hook-form在Next.js 14中创建通用表单组件?

如何使用另一个类型的属性中的类型

您可以创建一个类型来表示打字员吗

如何使用属性作为具有Generics的TypScript类中的类型守护?

React typescribe Jest调用函数

单击并移除for循环中的一项也会影响另一项

对数组或REST参数中的多个函数的S参数进行类型判断

使用打字Angular 中的通用数据创建状态管理

使用2个派生类作为WeakMap的键

尽管对象的类型已声明,但未解析的变量<;变量

按函数名的类型安全类型脚本方法包装帮助器

如何键入派生类的实例方法,以便它调用另一个实例方法?

如何在本地存储中声明该类型?

如何在Vue动态类的上下文中解释错误TS2345?

React中的效果挂钩在依赖项更新后不会重新执行

如何使用动态生成的键和值定义对象的形状?

React HashRouter,单击导航栏时页面重新加载出现问题