Search code examples
typescript

How to write dynamic key for interface using modern typescript?


How can I write this to achieve the same result as the example below, allowing me to have two keys to choose from?

export interface RTCPeerExchange {
  from: string;
  [offer|answer]: RTCSessionDescriptionInit;
}

I know I can use a type to achieve this, but is there a way to achieve the same using an interface?

type RTCPeerExchange = {
    from: string;
    answer: RTCSessionDescriptionInit;
}|{
    offer: RTCSessionDescriptionInit;
    from: string;
}

Solution

  • There might be a way to do it, via Generic Interface.

    interface RTCPeerExchange<T extends "offer" | "answer"> {
      from: string;
      type: T;
      data: T extends "offer" ? RTCSessionDescriptionInit : RTCSessionDescriptionInit;
    }
    

    Check if this helps.