Last active
August 27, 2019 21:20
-
-
Save jednano/f656ce7317533a6db6a80b070d2a6b80 to your computer and use it in GitHub Desktop.
TypeScript vs. JavaScript
This file contains hidden or 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
// @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, | |
}) | |
}) |
This file contains hidden or 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
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