
我想知道如何將值分配給依賴于同一物件內的另一個鍵的鍵。在這種情況下,我想說如果動物有主人它不是食物,但如果它沒有主人它就是食物。所以在我的例子中,物件動物應該評估為真,動物 2 應該評估為假,但他們沒有。
> I have tried isFood: animal.owner ? false: true
> I have tried isFood: animal.hasOwnProperty("owner") ? false: true
> I have tried isFood: "owner" in animal ? false: true
> I have tried isFood: this.owner ? false: true
interface personInterface {
name: string,
age: number,
isMember: boolean
};
interface animalInterface<T> {
owner?: T,
sound: string,
species: string,
isFood: boolean
}
let person: personInterface;
person = {
name: "justin",
age: 30,
isMember: true
}
let animal: animalInterface<personInterface>;
let animal2: animalInterface<personInterface>;
animal = {
owner: {...person},
sound: "Woof",
species: "Dog",
isFood: this.owner ? false: true
}
animal2 = {
sound: "Woof",
species: "Dog",
isFood: this.owner ? false: true
}
uj5u.com熱心網友回復:
this可能會因使用位置、函式內部或全域而異。為了參考當前物件并仍將鍵作為屬性訪問,您可以使用get如下所示的訪問器。您可以在此處閱讀有關get訪問器的更多資訊。
animal = {
owner: { ...person },
sound: "Woof",
species: "Dog",
get isFood() {
// Here this refers to current object
return this.owner ? false : true
}
}
animal2 = {
sound: "Woof",
species: "Dog",
get isFood() {
return this.owner ? false : true
}
}
console.log(animal.isFood);
console.log(animal2.isFood);
uj5u.com熱心網友回復:
為了實作它,您需要使用有區別的聯合:
interface PersonInterface {
name: string,
age: number,
isMember: boolean
};
interface AnimalInterfaceBase<T> {
owner?: T,
sound: string,
species: string,
isFood: boolean
}
type WithOwner<T> = {
owner: T,
sound: string,
species: string,
isFood: false
}
type WithoutOwner = {
sound: string,
species: string,
isFood: true
}
type AnimalInterface<T> = WithOwner<T> | WithoutOwner
let person: PersonInterface;
person = {
name: "justin",
age: 30,
isMember: true
}
let animal: AnimalInterface<PersonInterface>;
let animal2: AnimalInterface<PersonInterface>;
animal = {
owner: person,
sound: "Woof",
species: "Dog",
isFood: false
}
animal2 = {
owner: person, // expected error
sound: "Woof",
species: "Dog",
isFood: true
}
操場
PS 習慣上將介面名稱大寫。
uj5u.com熱心網友回復:
在這種情況下,您可以使用標記聯合型別。基本上,您創建兩個介面并通過屬性識別它們,在您的情況下isFood:
interface BaseAnimalInterface {
sound: string;
species: string;
isFood: boolean;
}
interface AnimalInterface extends BaseAnimalInterface {
isFood: true;
}
interface PetInterface<T = PersonInterface> extends BaseAnimalInterface {
owner: T;
isFood: false;
}
type AnimalType = AnimalInterface | PetInterface;
然后,如果您在if/switch陳述句中檢查該屬性,您將獲得正確的型別:
function playSound(animal: AnimalType): void {
if (animal.isFood) {
// Casted automatically to `AnimalInterface`
} else {
// Casted automatically to `PetInterface`
}
}
完整的例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364360.html
標籤:javascript 打字稿 javascript对象
