我有一個用于定義屬性的通用介面(假設它是一個Animal)。
然后我有這個介面的擴展,它有額外的不同欄位。
我想定義一個獲取動物實體、傳播它并決議特定欄位的函式。
結果值應與輸入值相同;但是我收到一個錯誤,因為并非所有動物都是平等的:P
如何使用擴展運算子并仍然回傳相同的型別?
interface AnimalProps { name: string; size: string; }
class Dog implements AnimalProps {
name: string;
size: string;
bark(): void { console.log(`${this.name} says: 'woof'`); }
constructor(name: string, size: string) {
this.name = name;
this.size = size;
}
}
class Bird implements AnimalProps {
name: string;
size: string;
fly(): void { console.log(`${this.name} says: 'I love flying'`); }
constructor(name: string, size: string) {
this.name = name;
this.size = size;
}
}
type Animal = Dog | Bird;
function addSizeUnits(animal: Animal): Animal {
// Property 'fly' is missing in type '{ size: string; name: string; }' but required in type 'Bird'.
return { ...animal, size: `${animal.size} meters` };
}
顯然我在這里簡化了現有的(遺留)代碼,但底線是我確實需要使用fly,bark因此我需要實際的聯合型別——而不是基本的Animal.
uj5u.com熱心網友回復:
通用函式應該在這里作業。就像是:
function addSizeUnits<T extends Animal>(animal: T) {
return { ...animal, size: `${animal.size} meters` };
}
請注意,我洗掉了回傳型別注釋,因為型別推斷應該為您解決這個問題,但是如果您想將其添加回來,您可以使用更正之類的東西,T & { size: string }T應該沒問題,因為您已經size在AnimalProps.
uj5u.com熱心網友回復:
這可以通過使用通用約束輕松解決:
function addSizeUnits<A extends Animal>(animal: A): A {
return { ...animal, size: `${animal.size} meters` };
}
這可確保您的引數型別和回傳型別是相同型別的Animal.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/486405.html
標籤:javascript 打字稿 联合类型
上一篇:如何從fs.unlink回傳承諾
