Last active
July 13, 2020 20:54
-
-
Save tcodes0/35f20b8b3f569daff11a2eaf21f74bc9 to your computer and use it in GitHub Desktop.
Typescripting Twitter snippets part 1
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
/************************************************************* | |
* https://twitter.com/marcelcruz/status/1282005231065341953 * | |
*************************************************************/ | |
/** | |
* original js | |
*/ | |
const capitalize = ([firstLetter, ...rest]) => { | |
return firstLetter.toUpperCase() + rest.join('') | |
} | |
/** | |
* typescript | |
*/ | |
const capitalize = ([firstLetter, ...rest]: string) => { | |
return firstLetter.toUpperCase() + rest.join('') | |
} | |
/********************************************************************** | |
* https://twitter.com/gustavo_pch/status/1282121799749296128/photo/1 * | |
**********************************************************************/ | |
/** | |
* some types for context that I wrote, not sure if correct | |
*/ | |
type Query = string[] | |
type ViewsDefinition = { | |
foo: { | |
queries: Query | |
}, | |
bar: { | |
queries: Query | |
} | |
} | |
const application = { | |
views: { | |
foo: { | |
queries: ['queries'], | |
}, | |
bar: { | |
queries: ['queries'], | |
}, | |
}, | |
} | |
/** | |
* original ts | |
*/ | |
const views = Object.entries(application.views).reduce( | |
(acc, [viewName, view]) => { | |
acc[viewName as keyof ViewsDefinition] = view.queries | |
return acc | |
}, | |
{} as { | |
[viewName in keyof ViewsDefinition]: ViewsDefinition[viewName]['queries'] | |
} | |
) | |
/** | |
* typescript | |
*/ | |
const views = Object.entries(application.views).reduce<Record<keyof ViewsDefinition, Query>>( | |
(acc, [viewName, view]) => { | |
acc[viewName] = view.queries | |
return acc | |
}, | |
{} as Record<keyof ViewsDefinition, Query> | |
) | |
/** | |
* How does record work? | |
*/ | |
type Obj = { [key: string]: boolean } | |
type SameObj = Record<string, boolean> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment