Skip to content

Instantly share code, notes, and snippets.

@jpkempf
Created April 23, 2021 15:18
Show Gist options
  • Save jpkempf/f95fec18dd7d6c1fd79dad14e19f21fe to your computer and use it in GitHub Desktop.
Save jpkempf/f95fec18dd7d6c1fd79dad14e19f21fe to your computer and use it in GitHub Desktop.
TypeScript magic with Extract
// source: https://twitter.com/mpocock1/status/1385610014639988739
const fields = [{
inputType: 'text',
label: 'ID',
name: 'id'
}, {
inputType: 'text',
label: 'Description',
name: 'description'
}, {
inputType: 'number',
label: 'Price',
name: 'price'
}] as const
type Field = (typeof fields)[number]
type Item = { [K in Field['name']]: Extract<Field, { name: K }> extends { inputType: 'number' } ? number : string }
const item: Item = {
description: 'yeah',
id: 'id',
price: 12
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment