Skip to content

Instantly share code, notes, and snippets.

View vinhlee95's full-sized avatar
🎯
Focusing

Vinh Le vinhlee95

🎯
Focusing
View GitHub Profile
const getKeys = (obj: unknown) => {
return Object.keys(obj as object) // <- cast the type to be object
}
const getObject = (): object | undefined => {
// some code that return EITHER an object OR undefined 💣💣💣
}
getKeys(getObject()) // <- 💣💥 when getObject() returns undefined
// Anything is assignable to unknown
const foo: unknown = 1 // <- we can assign a number to a unknown var
const bar: unknown = true // <- same with other primitive types such as boolean
// But unknown isn’t assignable to anything but itself
const myString: string = foo // <- ⛔️⛔️⛔️ unknown type is not assignable to string type
const isGreaterThan10 = (val: unknown) => val > 10 // <- ⛔️⛔️⛔️ because val has unknown type
@vinhlee95
vinhlee95 / gist:203224beb49988a9c5146edb4f00629b
Last active January 17, 2022 06:02
The unknown type in TypeScript

The unknown type in TypeScript

The unknown mistery

When I first onboarded TypeScript world from JavaScript, one of the most confusing thing is the unknown type. Remember when your coworkers write something like:

const foo = () => bar as unknown as any // <- 🤷🏻‍♂️🤷🏻‍♂️🤷🏻‍♂️

Let's take a look at TypeScript official documentation:

Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
AvailabilityZone: "eu-north-1a"
ImageId: "ami-0c5254b956817b326"
InstanceType: "t3.micro"
KeyName: "ec2-general"
SecurityGroups:
- !Ref HTTPSecurityGroup
const state = {
idle: "idle",
fetching: "fetching",
success: "success",
error: "error"
};
const todoActions = {
fetchTodos: "fetchTodos",
cancelFetching: "cancelFetching",
functions:
todos:
handler: src/todos/todos.handler
events:
http: GET /todos
import {from} from 'rxjs/operators'
const fetchCakesPromise = fetch(getCakesEndpoint, {method: 'GET'}).then(res => res.data.cakes)
// Get cakes stream creation 🌈
const cakeSource = from(fetchCakesPromise)
// Subscribe cake data and consume received cakes 🍽
cakeSource.subscribe(console.log)
import { Observable } from 'rxjs'
const observable = new Observable(observer => {
const array = [1,2,3,4,5]
array.forEach(number => {
if(!isOdd(number)) {
observer.error('Invalid even number')
}
observer.next(number)
@vinhlee95
vinhlee95 / complicated-stream.js
Created September 24, 2019 09:02
Describe how RxJS handles a complicated data stream
keyPressSources.pipe(
// Input handlers to take input value for searching
switchMap(value => {
return from(fetchCakesByName(value)).pipe(
// Only make an API request for searching after 0.5s since user stopped pressing a key
debounce(0.5),
// Retry 3 times if an API request fails
retry(3),
// Cancel the search when press Esc or clear input
takeUntil(value => value === 'Esc' || value === ''),
@vinhlee95
vinhlee95 / README.md
Created January 5, 2019 18:26 — forked from hofmannsven/README.md
My simply MySQL Command Line Cheatsheet