Skip to content

Instantly share code, notes, and snippets.

@lukeknxt
Created November 25, 2021 12:00
Show Gist options
  • Save lukeknxt/cd6c3898f6b7795ebfa13413139eccbd to your computer and use it in GitHub Desktop.
Save lukeknxt/cd6c3898f6b7795ebfa13413139eccbd to your computer and use it in GitHub Desktop.
WTF TypeScript
interface Service {
update(obj: { id?: string }): void;
// changing this to a function type `update: (obj: {id?: string}) => void` works
// and causes the implementation not to type-check
}
class ServiceImpl implements Service {
// somehow this is a valid implementation
update(obj: { id: string }): void {
// `id` can never be undefined or null here according to the type system
console.log(typeof obj.id); // definitely string surely!
}
}
function program(service: Service): void {
return service.update({}); // didn't pass an `id`
}
// prints `undefined` from an implementation where it shouldn't be possible
program(new ServiceImpl());
@lukeknxt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment