javascript - Angular2/TypeScript:錯誤 TS2345:型別 'String' 的參數無法指派給型別 'string' 的參數
我有以下的程式碼,我正在使用它來建立一個賭場管理系統:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { SearchService } from './search.service';
import { Data } from './datatypings';
@Component({
moduleId: module.id,
selector: 'casino-search',
templateUrl: 'search.component.html',
styleUrls: [ 'search.component.css' ],
providers: [SearchService]
})
export class SearchComponent implements OnInit {
data: Observable<Data[]>;
private searchTerms = new Subject<String>();
constructor(
private searchService: SearchService,
private router: Router) {}
// Push a search term into the observable stream
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.data = this.searchTerms
.debounceTime(150) // wait for 150ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time
// return the http search observable
? this.searchService.search(term)
// or the observable of empty data if no search term
: Observable.of<Data[]>([]))
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Data[]>([]);
});
}
gotoDetail(data: Data): void {
let link = ['/detail', data.id];
this.router.navigate(link);
}
}
然而,當我嘗試將這段程式碼從 TypeScript 轉譯為 JavaScript 時,我收到此錯誤:
app/data/search.component.ts(37,37): error TS2345: Argument of type 'String' is not assignable to parameter of type 'string'.
'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
現在,我已經簡單地通過將 String 改為 string 在尖括號內修復了錯誤,但我希望將來能夠繼續進行而不產生類似的錯誤,也希望寫出我能寫的最佳程式碼……所以我想知道是否有人可以為我釐清這一點:
我想我明白帶有包裝類的參數是什麼,它是封裝原始類並提供某種額外的、通常與介面相關的行為(如果我錯了請指正),我也明白為什麼將本質上聲明為更廣泛類型的變量內容賦值給更簡單的原始類可能不可行,還有錯誤訊息的另一個方面引起了我的興趣,那就是:
為什麼在 Angular2/Typescript 中,在像錯誤所暗示的這種一般性情況下,使用類型 'string' 會比使用類型 'String' 更可取?是什麼使這種方式更有優勢?
答案#1
private searchTerms = new Subject<String>();
將它改為
private searchTerms = new Subject<string>();
String 是一個 class,而 string 是一個 datatype。
