2016-04-16 62 views
13

好吧,这是我的第一天使用打字机做一些Angular 2,我尝试做一个简单的getter和setter服务。Typescript getter和setter错误

import {Injectable} from "angular2/core"; 

@Injectable() 
export class TodoService { 

    private _todos:Array = []; 

    get todos():Array { 
    return this._todos; 
    } 

    set todos(value:Array) { 
    this._todos = value; 
    } 

} 

任何人都可以解释为什么打字稿编译器抛出下面的错误,因为我认为它应该没问题。

ERROR in [default] /Users/testguy/WebstormProjects/angular2-seed/src/app/services/todo-service.ts:6:17 
Generic type 'Array<T>' requires 1 type argument(s). 

ERROR in [default] /Users/testguy/WebstormProjects/angular2-seed/src/app/services/todo-service.ts:8:14 
Generic type 'Array<T>' requires 1 type argument(s). 

ERROR in [default] /Users/testguy/WebstormProjects/angular2-seed/src/app/services/todo-service.ts:12:18 
Generic type 'Array<T>' requires 1 type argument(s). 

回答

10

你应该真正需要的,何况你要哪一种Array而定义它,MyClass可以string/number(数据类型)

代码

export class TodoService { 

    private _todos:Array<MyClass> = []; 

    get todos():Array<MyClass> { 
    return this._todos; 
    } 

    set todos(value:Array<MyClass>) { 
    this._todos = value; 
    } 

} 
+0

如果有任何其他人绊倒因此您需要将类型定义为数组,然后在<>中创建一个类,该类是描述数组项的结构的模型。 –