Skip to content

Instantly share code, notes, and snippets.

@angelikatyborska
Last active February 16, 2023 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelikatyborska/5f9a46910a0f3f6d4409fe203a74a0ba to your computer and use it in GitHub Desktop.
Save angelikatyborska/5f9a46910a0f3f6d4409fe203a74a0ba to your computer and use it in GitHub Desktop.
TypeScript tasks
// Task 1:
// copy-paste start ----------------------------------------
// TODO: define function argument type
function addOne(numberOrNumbers) {
if (typeof numberOrNumbers === 'number') {
return numberOrNumbers + 1
} else {
return numberOrNumbers.map(number => number + 1)
}
}
addOne(100)
addOne([3, 4, 5])
// copy-paste end ----------------------------------------
// Task 2:
// copy-paste start ----------------------------------------
// TODO: define missing LoggerFunction and User types
function inspectUser(loggerFunction: LoggerFunction, user: User) {
let userDescription = user.fullname ? user.fullname : user.nickname
if (user.admin) {
userDescription = `[admin] ${userDescription}`
}
loggerFunction(userDescription)
}
inspectUser(console.log, { nickname: 'css-queen-1993' })
inspectUser(console.log, { nickname: 'munchy-box-lover', fullname: "James M." })
inspectUser(console.log, { nickname: 'mihai_t', admin: true })
// copy-paste end ----------------------------------------
// Task 3 - ADVANCED!
// copy-paste start ----------------------------------------
type DarkPaletteColorKeyword = 'black' | 'gray' | 'pink'
type LightPaletteColorKeyword = 'white' | 'gray' | 'blue'
// TODO: define a generic Theme type
// that's an object whose keys are of the given variable type
// and that variable type must extend the string type (`extends string`)
const colorKeywordToHexTheme1: Theme<DarkPaletteColorKeyword> = {
'black': '#001100',
'gray': '#555555',
'pink': '#ffc0cb'
}
const colorKeywordToHexTheme2: Theme<LightPaletteColorKeyword> = {
'white': '#ffffff',
'gray': '#ccccc',
'blue': '#244ba5'
}
// TODO: add type annotations to make this a generic function
// that takes two arguments:
// - first, the colorKeyword argument of the given variable type
// - second, a theme argument of the generic Theme type whose keys are of the given variable type
function colorKeywordToHex(colorKeyword, theme) {
return theme[colorKeyword]
}
colorKeywordToHex('pink', colorKeywordToHexTheme1)
colorKeywordToHex('white', colorKeywordToHexTheme2)
// comment this out to see an error
// colorKeywordToHex('pink', colorKeywordToHexTheme2)
// copy-paste end ----------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment