Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidystephenson/ca7090ee54913efdcc8d5bb3456eb05d to your computer and use it in GitHub Desktop.
Save davidystephenson/ca7090ee54913efdcc8d5bb3456eb05d to your computer and use it in GitHub Desktop.
interface Tree {
branches: number
species: string
}
interface Vehicle {
position: number
speed: number
}
interface Animal {
legs: number
speed: number
}
const oak = {
branches: 10,
species: 'oak'
}
const willow = {
branches: 100,
species: 'willow'
}
const scionIq: Vehicle = {
position: 0,
speed: 80
}
function describeTree<K extends keyof Tree>(tree: Tree, key: K) {
const value = tree[key]
const message = `The ${key} of this tree is ${value}`
console.log(message)
}
describeTree<'branches'>(oak, 'branches')
function describeWithSpeed <T extends { speed: number }> (t: T, key: keyof T & string) {
const value = t[key]
const message = `The ${key} is ${value}, and the speed is ${t.speed}`
console.log(message)
}
describeWithSpeed(oak, 'branches')
describeWithSpeed(scionIq, 'position')
const cheetah: Animal = { legs: 4, speed: 90 }
describeWithSpeed(cheetah, 'legs')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment