Skip to content

Instantly share code, notes, and snippets.

@brahmlower
Created June 19, 2022 03:53
Show Gist options
  • Save brahmlower/2424958b221c994459e282e18e55f3a1 to your computer and use it in GitHub Desktop.
Save brahmlower/2424958b221c994459e282e18e55f3a1 to your computer and use it in GitHub Desktop.
Omitting `symbol` and `number` from `keyof` on generic type using `Exclude`
// Example showing usage of typescripts `Exclude` utility type.
// Typescript playground link: https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBAQwG4JAgJmKBJdcC8cAjAEwDMA3MKJLIgA70A2AplAMoCeAtgXF9wBGYJgAoARAkaso4gJTUAlhBgsATgDNULOADE1AV0UwAQgigBrFvADewOA7gBtKczYCAugC44EA0PV7RzA1BAgAczYfPwC1IId6FgQ1KGj-QUDHZ2RUDCxcb190wIBfag0DCBAYRUg4DUNjABUwAFFuMAArRVEGoxgAOQRuFh9YNWVwuTGYCYi4OyyoAHdjEAALOF7GweGWOQX4rLg0KB1xELDI2S8j48c1awM1CDhxQB4NwCl98TvHU-PEskbr97o8YM9Xh9AAr7P3uDnQLC0BiYMFucOOYIhbwAPJULBAwMsIAA+WGOMplYAVKo1Or0OYwfT9IYjbFNAA0cAA0nAWAAPVQQdBQOCtPkgJgGBHYqycMAaOAcuBQHjCJhwAA+RVixOJ22Zex8XM5gnMVlRiumytmk0OWVY8D6xnaXUUfCdMBaLu6+uMLP2Rwd9R2A38fFNlmsTg9-o8R0xLzgAAMACQ2D3exQlOBpmP+EpJ4CUoMR80+JnGMyR+CERaOFzSdw8QoAVnZR0uESixHbWUBKR8ZF79ZyaEwOHQhQALO3KQB6OeitRqEIi1Ywda3BeOACCanC-hYKjg8rgME4iTgAHJJI3ZFe4IoRQT4OYoIpwhAEIJWGewHB6GSPZVDUE8FXPS8b07a5xE1N5+3vYAFyQxdwGgEQWAAOiYMBwlEellEZEM9gkVwZHEE0zWsOQFBQpcVxSOB103OiHD3A8RmPU8IJ0K9KkUABHAwdBVIQRAfJ9fDAV8oHfT9v1-GB-0A0IRhAsCzwvXiLlCLtZDg8QEPEK9MJQui0KgDDsNw-CGQrXYRlEMim24Sjqxo6ht1aZdVyY4wWO3Nj90PLjwK069SDICTn2kxBZI-L8fx0JSAKAtT1A0njrx0q42FgrVDKSFJjLM7cLKsnC8IIlR7P9JyUDHfJ0Dc80PLogAFBlUlYt53ihOAyB+crWGsqq7OIxzCqBCi4FLaiFCAA
const avacadosId = 123;
const applesSym = Symbol("apples")
interface FruitBasket {
[applesSym]: number
oranges: number
pears: number
[avacadosId]: number
}
function fruitToEmoji(fruitName: string): string {
switch (fruitName) {
case "oranges":
return "🍊"
case "pears":
return "🍐"
default:
return "<unknown>"
}
}
function printFruitName<T, K extends Exclude<keyof T, symbol | number>>(fruitName: K, basket: T): string {
let fruitEmoji = fruitToEmoji(fruitName)
let fruitNum = basket[fruitName]
return `${fruitEmoji} ${fruitNum}`
}
let basket: FruitBasket = {
[applesSym]: 5,
oranges: 1,
pears: 3,
[avacadosId]: 4,
}
// Errors with:
// Argument of type '"apples"' is not assignable to parameter of type '"oranges" | "pears"'
//
// console.log(printFruitName("apples", basket))
// Errors with:
// Argument of type 'unique symbol' is not assignable to parameter of type '"oranges" | "pears"'.
//
// console.log(printFruitName(applesSym, basket))
// Errors with:
// Argument of type '123' is not assignable to parameter of type '"oranges" | "pears"'
//
// console.log(printFruitName(avacadosId, basket))
// Prints:
// "🍐 3"
console.log(printFruitName("pears", basket))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment