Skip to content

Instantly share code, notes, and snippets.

@jahredhope
Last active November 14, 2019 11:05
Show Gist options
  • Save jahredhope/ec4ee7a19ee00240a0ca365cc4e759b7 to your computer and use it in GitHub Desktop.
Save jahredhope/ec4ee7a19ee00240a0ca365cc4e759b7 to your computer and use it in GitHub Desktop.
Typescript Example - Generic items & render
/**
* A TypeScript example of a generic type used
* by a function where the type passed
* into the function allows TypeScript to infer the
* type of another value passed in.
*/
interface Params<I> {
items: I[];
render: (item: I) => void;
}
function foo<I>({ items, render }: Params<I>) {
items.forEach(render);
}
// Alternative: Arrow syntax
// Note that this syntax doesn't work in tsx files due to conflicts with JSX syntax
// const foo = <I>({ items, render }: Params<I>) => {
// items.forEach(render);
// };
interface Square {
h: number;
w: number;
}
interface Circle {
r: number;
}
const circles: Circle[] = [{ r: 1 }, { r: 2 }];
const squares: Square[] = [
{ h: 1, w: 2 },
{ h: 3, w: 4 },
];
foo({
// circles has the type Circle[]
items: circles,
// so the render function's first parameter is assumed to be a Cirlce
render: circle => console.log(`Circle with radius ${circle.r}`),
});
foo({
// Now squares has the type Square[]
items: squares,
// so the render function's first parameter is assumed to be a Square
render: square => console.log(`Square of size ${square.h} x ${square.w}`),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment