typescript 打字稿 getter 和 setter 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36664824/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:25:05  来源:igfitidea点击:

Typescript getter and setter error

typescriptangularangular2-services

提问by rtn

Ok it's my first day doing some Angular 2 using typescript and I am try to make a simple getter and setter service.

好的,这是我第一天使用 typescript 做一些 Angular 2,我正在尝试制作一个简单的 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;
  }

}

Can anyone explain why the Typescript compiler is throwing the following error as I think it should be ok.

任何人都可以解释为什么 Typescript 编译器会抛出以下错误,因为我认为应该没问题。

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).

采纳答案by Pankaj Parkar

You should really need to mention which kind of Arrayyou want while defining it, MyClasscan be string/number(datatype)

你真的需要Array在定义它时提到你想要哪种类型,MyClass可以是string/ number(数据类型)

Code

代码

export class TodoService {

  private _todos:Array<MyClass> = [];

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

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

}