Home > Blockchain >  How to get a different return type according to the object accessing key?
How to get a different return type according to the object accessing key?

Time:12-11

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?

CodePudding user response:

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
  • Related