Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

316
Visualizações
How to assign a conditional value to a key based on another of its properties

My Problem

I'm wondering how I can assign a value to a key that depends on another key inside that same object. In this case I want to say if animal has owner it is NOT food but if it does not have an owner it IS food. So in my example the object animal should evaluate to true and animal2 should evaluate to false but they don't.

> 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 
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In order to achieve it, you need to use discriminated unions:

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
}

Playground

P.S. It is conventional to capitalize interface names.

about 4 years ago · Juan Pablo Isaza Relatório

0

this may vary depending upon where it is used, inside a function or globally. In order to refer the current object and still access the key as a property, you can use get accessor like below. You can read more about get accessor here.

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);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use tagged union types in this case. Basically you create two interfaces and discern them by a property, in your case 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;

Then, if you check into that property on an if/switch statement you'll get the proper type:

function playSound(animal: AnimalType): void {
    if (animal.isFood) {
        // Casted automatically to `AnimalInterface`
    } else {
        // Casted automatically to `PetInterface`
    }
}

Full example.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda