typescript 带有angular2的打字稿中的对象类型数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37982409/
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
array of object type in typescript with angular2
提问by diEcho
in my angular application I want to use an array of object of id and role in below manner
在我的角度应用程序中,我想以下面的方式使用一组 id 和角色的对象
let userRole: Array<...> = [
{ id: 1, name: 'Admin' },
{ id: 2, name: 'Super Admin' },
{ id: 2, name: 'User' },
{ id: 2, name: 'Watcher' }
];
BUT I am confused what need to fill up in place of ...?
但我很困惑需要填写什么来代替...?
Array < Object >
or Array <Any>
Array < Object >
或者 Array <Any>
Trial 1 :
试验 1:
var role = {
id: number;
name: string;
};
var role = {
id: number;
name: string;
};
and then Array <role>
but it gives error
然后Array <role>
但它给出了错误
Trial 2 :adding with different class file
试用 2:添加不同的类文件
role.ts
角色.ts
export class Role {
constructor(
public id: number,
public name: string
) { }
}
and add in my file as
并将我的文件添加为
import { Role } from './role';
export class HeroFormComponent {
let userRole: Array<Role> = [
{ id: 1, name: 'Admin' },
{ id: 2, name: 'Super Admin' },
{ id: 2, name: 'User' },
{ id: 2, name: 'Wacher' }
];
But gives error
但给出错误
Error: SyntaxError: Unexpected strict mode reserved word
错误:SyntaxError:意外的严格模式保留字
回答by Ryan Cavanaugh
Your first and best option is to simply not have a type annotation:
您的第一个也是最好的选择是根本没有类型注释:
let userRole = [
{ id: 1, name: 'Admin' },
{ id: 2, name: 'Super Admin' },
{ id: 2, name: 'User' },
{ id: 2, name: 'Watcher' }
];
The inferred type of userRole
will be Array<{ id: number, name: string }>
.
的推断类型userRole
是Array<{ id: number, name: string }>
。
If you really want a type annotation for whatever reason, you can write either
如果您出于任何原因确实想要一个类型注释,您可以编写
let userRole: { id: number, name: string }[] = [ ...
or
或者
let userRole: Array<{ id: number, name: string }> = [ ...
These two syntaxes are identical in behavior.
这两种语法在行为上是相同的。
If you're going to be using this type a lot, you might want to make an interface for it so you can re-use the name in other places:
如果你要经常使用这个类型,你可能想为它制作一个接口,这样你就可以在其他地方重用这个名字:
interface Role {
id: number;
name: string;
}
Now you can write
现在你可以写
let userRole: Role[] = [ ...
When you declare an initialized field in a class, you do not use var
or let
:
在类中声明已初始化的字段时,不要使用var
或let
:
export class HeroFormComponent {
userRole = [
{ id: 1, name: 'Admin' },
{ id: 2, name: 'Super Admin' },
{ id: 2, name: 'User' },
{ id: 2, name: 'Wacher' }
];
Again here, you can pick and choose which type annotation you'd like to have.
再次在这里,您可以选择您想要的类型注释。