Is it possible in Typescript to enforce a required key in an interface only when a generic is used?
I am exploring ways to define type restrictions for keys in interfaces specifically when utilizing generics.
For example:
interface IExample {
foo: string
}
/* Note that you cannot have two interfaces with the same name, this is just to illustrate the desired structure */
interface IExample<T> {
foo: string,
bar: T
}
/* Allowed */
const withoutBar: IExample {
foo: 'some string'
}
/* Not allowed because a generic for Bar has been provided */
const withoutBar: IExample<number> {
foo: 'some string'
}
/* Allowed */
const withBar: IExample<number> {
foo: 'some string',
bar: 1
};
/* Not allowed since no generic for Bar was passed in */
const withBar: IExample {
foo: 'some string',
bar: 1 // Error should occur for "bar" as no generic was used
};