Skip to content

Instantly share code, notes, and snippets.

@dsosby
Created March 11, 2019 22:42
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 dsosby/e5cde7581826677128e9aad15d037f56 to your computer and use it in GitHub Desktop.
Save dsosby/e5cde7581826677128e9aad15d037f56 to your computer and use it in GitHub Desktop.
TypeScriptConditionalType
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