Is there a way to make a property optional based on the generic type in TypeScript? I've attempted the following:
interface Option<T extends 'text' | 'audio' | 'video'> {
id: string;
type: T;
text: T extends 'text' ? string : undefined;
media: T extends 'audio' | 'video' ? T : undefined;
}
const option: Option<'text'> = { text: "test", type: "text", id: "opt1" };
Basically, the goal is to have the text
property only for Option<'text'>
and the media
property only for Option<'audio' | 'video'>
.
However, when compiling, an error is thrown by the TypeScript compiler:
Property 'media' is missing in type '{ text: string; type: "text"; id: string; }'
but required in type 'Option<"text">'.ts(2741)
What would be a good workaround for this situation?