Skip to content

Instantly share code, notes, and snippets.

@brasten
Last active January 14, 2019 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brasten/ab207397dec4cd3f64a5de9a594ac789 to your computer and use it in GitHub Desktop.
Save brasten/ab207397dec4cd3f64a5de9a594ac789 to your computer and use it in GitHub Desktop.
TypeScript - Less-permissive implementation of interface
// TypeScript v 3.2.2
//
// I feel like something along the way here should fail type-checking.
//
// The interface for Repository#saveFeed takes an attribute
// with an optional `feed` property. The implementation requires the
// `feed` property, and thus - I suppose - satisfies the requirement?
type FeedInfo = {
feed: {
sheetId: string;
budgetId: string;
};
};
type IFeedInfo = {
feed?: {
sheetId: string;
budgetId: string;
};
};
interface IFeedRepository {
saveFeed(feedInfo: IFeedInfo): void;
}
class FeedRepository implements IFeedRepository {
saveFeed(feedInfo: FeedInfo) {
console.log('This line will explode.' + feedInfo.feed.budgetId);
}
}
// This is where it starts to get a little bit weird in my mind.
// Despite explicitly implementing the interface, I'm not sure that
// FeedRepository can actually be considered an implementation of
// IFeedRepository, because ...
let repo: IFeedRepository = new FeedRepository();
repo.saveFeed({});
// ... this last line explodes. This explicitly should be ok according to the
// IFeedRepository contract, but explicitly should not be ok according
// to the FeedRepository contract. ?
{
"compilerOptions": {
"strict": true,
"noEmit": true,
},
"files": [
"index.ts"
],
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment