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

130
Visualizações
How to get a different return type according to the object accessing key?

Let me simply put it like,

interface PlanValue {
  planName: string;
  startDate: string;
} 

type DeviceKey = 'pc' | 'mobile' | 'laptop';

type PlanType = Record<DeviceKey, PlanValue>

interface Subscription {
  valid: boolean;
  plan: PlanType;
}

Let's say that a new device key called Kiosk is added to DeviceKey type.

But the return type of this key should be boolean.

For example

const subsc1: Subscription = new Subscription();
const subsc2: Subscription = new Subscription();
console.log(subsc1.plan.pc)    // type should be PlanValue
console.log(subsc2.plan.Kiosk) // type should be boolean

I can't change the Subscription.plan type to PlanType | boolean because it will break other codes that are referring to this type.

How can I get a different return type according to the accessing key during the runtime?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Use an intersection:

TS Playground link

interface PlanValue {
  planName: string;
  startDate: string;
} 

type DeviceKey = 'pc' | 'mobile' | 'laptop';

type PlanType = Record<DeviceKey, PlanValue> & { Kiosk: boolean };

interface Subscription {
  valid: boolean;
  plan: PlanType;
}

declare const s: Subscription;
s.plan.pc // PlanValue
s.plan.Kiosk // boolean
about 4 years ago · Santiago Gelvez 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