typescript 类型上不存在打字稿属性“长度”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39779750/
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 Property 'length' does not exist on type
提问by
I'm new to Typescript and have been trying to get the following snippet to work:
我是 Typescript 的新手,一直在尝试使以下代码段起作用:
quoteService.getQuoteOfTheDay()
.then(quotes => this.quote = quotes[Math.floor(Math.random() * quotes.length)]);
The idea is to randomly select a quote from the array.
这个想法是从数组中随机选择一个引用。
Instead I get the following error in Terminal Property 'length' does not exist on type 'Quote'.
相反,我在终端中收到以下错误 Property 'length' does not exist on type 'Quote'.
If I change quotes.length
to 4
the snippet works but I want to the function to figure out how many quotes there are and then randomly return a single one.
如果我更改quotes.length
为4
代码段有效,但我希望该函数计算出有多少引号,然后随机返回一个。
Here is the entire Component below.
下面是整个组件。
import { Component } from '@angular/core';
import { MaterialModule } from '@angular/material';
import { Http } from '@angular/http';
import { Quote } from './quote.model';
import { QuoteService } from './quote.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [QuoteService]
})
export class AppComponent {
title = 'App is running!';
quote: Quote;
constructor(quoteService: QuoteService) {
quoteService.getQuoteOfTheDay()
.then(quotes => this.quote = quotes[Math.floor(Math.random() * quotes.length)]);
}
}
The quote.service.tswas wrong
该quote.service.ts错了
getQuoteOfTheDay(): Promise<Quote> {
return this.http.get('quote.json').toPromise()
.then(response => response.json());
}
Should have been like this
应该是这样的
getQuoteOfTheDay(): Promise<any> {
return this.http.get('quote.json').toPromise()
.then(response => response.json());
}
采纳答案by Bergi
Your type for getQuoteOfTheDay(): Promise<Quote>
seems to be wrong. While the method name, method type and file name all suggest that the returned promise will fulfill with only a single quote, your component is using it as if it returned an array of quotes. You'll want to use
你的类型getQuoteOfTheDay(): Promise<Quote>
似乎是错误的。虽然方法名称、方法类型和文件名都表明返回的 promise 将仅使用单引号实现,但您的组件正在使用它,就好像它返回一个引号数组一样。你会想要使用
getQuotesOfTheDay(): Promise<[Quote]> {
// ^ ^ ^
return this.http.get('quotes.json').toPromise()
// ^
.then(response => response.json());
}
回答by ibejo
Try using quotes[].length since it appears to be an array.
尝试使用引号 [].length,因为它似乎是一个数组。