我有一個像這樣的通用介面
type myType =
{
value1:string;
value2:string;
}
和一個班級
class array<myType> extends Array<myType>
{
let a:myType;
a.value1 ==> error.
}
問題是在課堂上,myType 型別讀取不正確,因為它是另一回事,我該如何解決這個問題?
uj5u.com熱心網友回復:
要推斷出該陣列的元素MyType,請宣告一個具有擴展名的唯一類Array<MyType>。可以使用 參考陣列的各個元素this[index]。
這是一個示例(和一個操場鏈接):
type MyType = {
value1: string;
value2: string;
};
class MyTypeArray extends Array<MyType> {
getCombinedValues(index: number) {
// type of elementAtIndex is inferred as MyType
const elementAtIndex = this[index];
return `${elementAtIndex.value1} ${elementAtIndex.value2}`
}
}
const myTypeArray = new MyTypeArray({ value1: 'Hello', value2: 'world' });
// Prints 'Hello world'
console.log(myTypeArray.getCombinedValues(0));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/372519.html
