Forcing excess-property checking on variable passed to TypeScript function

Hope this helps, this will cause it to fail. The underlying cause here is Typescripts reliance on structural typing which is alot better than the alternative which is Nominal typing but still has its problems.

type StrictPropertyCheck<T, TExpected, TError> = Exclude<keyof T, keyof TExpected> extends never ? {} : TError;

interface Animal {
    speciesName: string
    legCount: number,
}

function serializeBasicAnimalData<T extends Animal>(a: T & StrictPropertyCheck<T, Animal, "Only allowed properties of Animal">) {
    // something
}

var weirdAnimal = {
    legCount: 65,
    speciesName: "weird 65-legged animal",
    specialPowers: "Devours plastic"
};
serializeBasicAnimalData(weirdAnimal); // now correctly fails

Leave a Comment