Skip to content

Instantly share code, notes, and snippets.

@dsosby dsosby/notgoodbye.ts
Created Mar 11, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.