Skip to content

Instantly share code, notes, and snippets.

@jednano
Last active August 27, 2019 21: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 jednano/f656ce7317533a6db6a80b070d2a6b80 to your computer and use it in GitHub Desktop.
Save jednano/f656ce7317533a6db6a80b070d2a6b80 to your computer and use it in GitHub Desktop.
TypeScript vs. JavaScript
// @ts-check
/**
* @typedef {{ items: Array<CartItem> }} Cart
* @typedef {{
* sku: string,
* name: string,
* price: number,
* color?: Color,
* size?: Size,
* quantity: number
* }} CartItem
* @typedef {'red' | 'blue'} Color
* @typedef {'S' | 'M' | 'L'} Size
*/
/**
* @param {string} sku
* @param {CartItem} options
* @returns {Promise<Array.<CartItem>>}
*/
async function _addToCart(sku, options = {}) {
return Promise.resolve([
{
sku: '123',
name: 'shirt',
price: 15,
color: 'red',
size: 'L',
quantity: 1,
},
{
sku: '456',
name: 'pants',
price: 45,
color: 'blue',
size: 'S',
quantity: 2,
},
{ sku, ...options },
])
}
/**
* @param {(addToCart: typeof _addToCart) => Promise<Array.<CartItem>>} callback
*/
export function onAddToCart(callback) {
return callback(_addToCart)
}
onAddToCart(async addToCart => {
return addToCart('xyz', {
color: 'red',
size: 'M',
quantity: 3,
})
})
interface Cart {
items: CartItem[]
}
interface CartItem {
sku: string
name: string
price: number
color?: Color
size?: Size
quantity: number
}
type Color = 'red' | 'blue'
type Size = 'S' | 'M' | 'L'
async function _addToCart(
sku: string,
options: Partial<Pick<CartItem, 'color' | 'size' | 'quantity'>> = {},
) {
return Promise.resolve<CartItem[]>([
{
sku: '123',
name: 'shirt',
price: 15,
color: 'red',
size: 'L',
quantity: 1,
},
{
sku: '456',
name: 'pants',
price: 45,
color: 'blue',
size: 'S',
quantity: 2,
},
{ sku, ...options } as CartItem,
])
}
export function onAddToCart(
callback: (addToCart: typeof _addToCart) => Promise<CartItem[]>,
) {
return callback(_addToCart)
}
onAddToCart(async addToCart => {
return addToCart('xyz', {
color: 'red',
size: 'M',
quantity: 3,
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment