Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!