Created
July 29, 2018 18:59
-
-
Save gsbelarus/1514d35106031d61fdbcd41d35072123 to your computer and use it in GitHub Desktop.
type checking for allowable football substitutions
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
type Player<Club extends string> = { | |
club: Club, | |
name: string | |
}; | |
function createPlayer<Club extends string>(club: Club, name: string): Player<Club> { | |
return { club, name }; | |
} | |
const maradona = createPlayer('Dynamo Brest', 'Maradona'); | |
const milevskij = createPlayer('Dynamo Brest', 'Milevskij'); | |
const ronaldo = createPlayer('Dynamo Minsk', 'Ronaldo'); | |
type Substitution<PlayerIn, PlayerOut> = { | |
playerIn: PlayerIn, | |
playerOut: PlayerOut | |
}; | |
function substitute<ClubOut extends string>(playerOut: Player<ClubOut>) { | |
return ( | |
<ClubIn extends ClubOut>(playerIn: Player<ClubIn>): Substitution<Player<ClubIn>, Player<ClubOut>> => | |
( | |
{ | |
playerIn, | |
playerOut | |
} | |
) | |
); | |
} | |
const s1 = substitute(milevskij)(maradona); // OK | |
const s2 = substitute(maradona)(ronaldo); // ERROR -- they are from different clubs! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment