Home > Blockchain >  Typescript not validating the contents of an object being spread to complete a type
Typescript not validating the contents of an object being spread to complete a type

Time:11-08

I have an interface IThing and several interfaces that extend Ithing: IThingA, IThingB, etc.

interface IThing{
    id: string;
}

interface IThingA extends IThing{
    a1: string;
    a2: number;
}

interface IThingB extends IThing{
    b1: string;
}

I have a generic function that creates an IThing given a set of props:

function createThing<T extends IThing>(
    props: any = {}
): T {
    const thing: T = {
        id: newId(),
        ...props
    };
    return thing;
}

When I call the function:

const a1: string = "red";
const a2: number = 10;
const props = {a1}; //forgot to include a2
const thing: IThingA = createThing<IThingA>(props);

I would like Typescript to warn me if props doesn't contain all the properties required for the specific IThing. In this case I forgot a2 for IThingA and Typescript doesn't warn.

How can I achieve this check?

CodePudding user response:

It seems that Omit<interface, id> will help you. So I Altered your code to match the requirements

function createThing<T extends IThing>(
    props: Omit<T, 'id'>
): T {
    const thing: T = {
        id: newId(),
        ...props
    } as T;
    return thing;
}

full example in Ts Playground

  • Related