Description
TypeScript Version: 3.1.1
Search Terms: extra property checks, explicit cast, exact type
Code
interface Switch {
on: boolean;
}
const a = <Switch>{on: false, blah: 123}; // no error, ¯\_(ツ)_/¯
const b: Switch = {on: false, blah: 123}; // error, may only specify known propery and blah is extra
Expected behavior:
Explicit cast should force extra property checks like the object literal does. I feel like TS team thinks this is intentional and may be a big breaking change.
Alternatively please give us an exact type if possible e.g StrictPropertyCheck<T>
so we can do something like const b = <StrictPropertyCheck<SwitchState>>{...}
This stackoverflow thread has some magic vodoo for forcing extra property checks for functions that take arguments. https://stackoverflow.com/questions/54775790/forcing-excess-property-checking-on-variable-passed-to-typescript-function
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
}
Would be nice if we could have a similar mapped type that worked for objects.
Actual behavior:
No error