I realize the "object literal may only specify known properties" doesn't work in all cases. In particular, it looks like it doesn't work when I pass the object literal through an identity-like function (playground link)
declare function setUser(arg: {name: string}): void;
declare function identity<T>(v: T): T;
setUser({name: 'a', age: 12}); // Error, good!
setUser(identity({name: 'a', age: 12})); // No error, sad.
const u = {name: 'a', age: 12};
setUser(u); // No error, but I'm used to this case already.
Is there a way to write identity
in a way that will get back the error?
In my actual codebase, I'm not using the identity function, but a slight variant (playground link):
declare function setUser(arg: {name: string}): void;
type NonNullable<T> = T extends null ? never : T;
export type NullableToOptional<T> = {
[K in keyof T]: null extends T[K] ? NonNullable<T[K]> | undefined : T[K];
};
export function toOptional<T>(x: T): NullableToOptional<T> {
return x as NullableToOptional<T>;
}
setUser({name: 'a', age: 12}); // Error, good!
setUser(toOptional({name: 'a', age: 12})); // No error, sad.