Created
April 23, 2021 15:18
-
-
Save jpkempf/f95fec18dd7d6c1fd79dad14e19f21fe to your computer and use it in GitHub Desktop.
TypeScript magic with Extract
This file contains 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
// 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