Created
March 11, 2019 22:42
-
-
Save dsosby/e5cde7581826677128e9aad15d037f56 to your computer and use it in GitHub Desktop.
TypeScriptConditionalType
This file contains hidden or 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 NotGoodbye<T> = T extends "goodbye" ? never : T; | |
type Salutation = "hello" | "goodbye"; | |
type AllPossibleWords = string | |
type AllPossibleWordsWithoutGoodbye = NotGoodbye<AllPossibleWords> | |
function neverSayBye(salutation: NotGoodbye<Salutation>, greetee: string) { | |
console.log(`${salutation} ${greetee}`) | |
} | |
neverSayBye('goodbye', 'David'); | |
neverSayBye('hello', 'David'); | |
fetch('/random/salutation') | |
.then(response => response.json()) | |
.then((randomSalutation: Salutation) => { | |
// The below fails to compile as we cannot assert "goodbye" is | |
// not the chosen salutation | |
neverSayBye(randomSalutation, 'David'); | |
}); | |
let someGreeting: AllPossibleWordsWithoutGoodbye = 'hello'; | |
let anotherGreeting: AllPossibleWordsWithoutGoodbye = 'goodbye'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment