In my coding project, I have defined an initial interface called IThing
, which serves as the base for several other interfaces such as IThingA
, IThingB
, and more.
interface IThing{
id: string;
}
interface IThingA extends IThing{
a1: string;
a2: number;
}
interface IThingB extends IThing{
b1: string;
}
A key function in my project is a generic function that is responsible for creating a specific type of IThing
by utilizing a given set of props
:
function createThing<T extends IThing>(
props: any = {}
): T {
const thing: T = {
id: newId(),
...props
};
return thing;
}
However, during a recent usage scenario, I encountered an oversight. I had missed including all necessary properties when calling the function:
const a1: string = "red";
const a2: number = 10;
const props = {a1}; // Importance of including `a2` forgotten
const thing: IThingA = createThing<IThingA>(props);
To prevent such oversights in the future, I aim to leverage TypeScript's type checking system to notify me if the provided props
lack essential properties required for the specific IThing
. As seen in this case where a2
was omitted for IThingA
.
Could you provide guidance on how I can implement this validation within Typescript?