Last active
January 14, 2019 18:34
-
-
Save brasten/ab207397dec4cd3f64a5de9a594ac789 to your computer and use it in GitHub Desktop.
TypeScript - Less-permissive implementation of interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. ? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters
{ | |
"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