typescript 打字稿接口初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23412033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
typescript interface initialization
提问by Giacomo Tagliabue
My level of typescript is 'ABSOLUTE BEGINNER' but I have a good OOP background. I am building an with typescript that reference an external t.ds
library that contains the following interface:
我的打字稿水平是“绝对初学者”,但我有很好的面向对象编程背景。我正在构建一个带有引用t.ds
包含以下接口的外部库的打字稿:
interface ISimpleObject {
foo: string;
bar?: any;
}
Now, if I want to call a method that has an IRequestConfig parameter, how do I create one? I can see different options:
现在,如果我想调用一个具有 IRequestConfig 参数的方法,我该如何创建一个?我可以看到不同的选项:
- Create a simple implementation of ISimpleObject. I don't like this approach because it looks like boilerplate code to me
don't initialize the object (I fear this could break something...):
var x :IsimpleObject; x.bar = 'xxx'; callMethod(x);
Cast a pojo:
var x :IsimpleObject = <IsimpleObject>{foo: 'yyy', bar:'xxx'};
I don't like this approach either because it doesn't enforce type safety...
- 创建 ISimpleObject 的简单实现。我不喜欢这种方法,因为对我来说它看起来像样板代码
不要初始化对象(我担心这会破坏某些东西......):
var x :IsimpleObject; x.bar = 'xxx'; callMethod(x);
投一个 pojo:
var x :IsimpleObject = <IsimpleObject>{foo: 'yyy', bar:'xxx'};
我也不喜欢这种方法,因为它不强制类型安全......
I guess this is a fairly trivial question and I am missing something trivial about typescript.
我想这是一个相当微不足道的问题,我错过了关于打字稿的一些微不足道的东西。
回答by sdrevk
Typescript2:
打字稿2:
const simpleObject = {} as ISimpleObject;
回答by WiredPrairie
If you have an interface like:
如果你有这样的界面:
interface ISimpleObject {
foo: string;
bar?: any;
}
This interface is only used at compile time and for code-hinting/intellisense. Interfaces are used to provide a rigorous and type-safe way of using an object with a defined signature in a consistent manner.
此接口仅用于编译时和代码提示/智能感知。接口用于提供一种严格且类型安全的方式,以一致的方式使用具有定义签名的对象。
If you have a function using the interface
defined above:
如果你有一个使用interface
上面定义的函数:
function start(config: ISimpleObject):void {
}
The TypeScript compile will fail if an object does not have the exact signature of the ISimpleObject
interface.
如果对象没有准确的ISimpleObject
接口签名,则 TypeScript 编译将失败。
There are multiple valid techniques for calling the function start
:
调用函数有多种有效技术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"));
Any time the signature doesn't match, the compile will fail:
任何时候签名不匹配,编译都会失败:
// compile fail
var bad = { foobar: 'bad' };
start( bad );
// compile fail
var bad: ISimpleObject = { foobar: 'bad' };
// and so on.
There is no "right" way to do it. It's a matter of style choice. If it were an object that was constructed (rather than just directly passed as a parameter), I'd normally declare the type:
没有“正确”的方法来做到这一点。这是风格选择的问题。如果它是一个构造的对象(而不是直接作为参数传递),我通常会声明类型:
var config: ISimpleObject = { foo: 'hello' };
That way code-completion/IntelliSense will work anywhere I used the config
variable:
这样代码完成/智能感知将在我使用config
变量的任何地方工作:
config.bar = { extra: '2014' };
There is no "casting" in TypeScript. It is called a type assertion and shouldn't be needed in the cases described here (I included an example above where it could be used). There's no need to declare the variable Type and then use an assertion in this case (as the type was already known).
TypeScript 中没有“强制转换”。它被称为类型断言,在此处描述的情况下不需要(我在上面包含了一个可以使用它的示例)。在这种情况下不需要声明变量 Type 然后使用断言(因为类型已经知道)。
回答by Amir Popovich
You can't create an instance of an interface since Typescript doesn't "translate" it into js. You can check the js that is created and you will see nothing in it. It's simple for compile errors, type safety and intelisense.
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();
您无法创建接口的实例,因为 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();