Skip to content

Instantly share code, notes, and snippets.

View charlypoly's full-sized avatar
🚀
Building thriving devtools

Charly Poly charlypoly

🚀
Building thriving devtools
View GitHub Profile
type UUID = string;
interface User {
id: UUID;
first_name: string;
last_name: string;
plan: 'free' | 'premium'
}
interface PremiumOptions {
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-6.ts
Created November 29, 2021 11:05
TypeScript type guard definition
function isPremiumUser(user: User): user is PremiumUser {
return user.plan === 'premium'
}
function isPremiumUser(user: User): user is PremiumUser {
return user.plan === 'premium'
}
function getPremiumOptions(user: User | PremiumUser): PremiumOptions | null {
if (isPremiumUser(user)) {
user
// `user` is of type `PremiumUser`
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-8.ts
Created November 29, 2021 11:08
TypeScript lodash's isString()
function isString(value?: any): value is string;
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-9.ts
Created November 29, 2021 11:10
TypeScript lodash `isString()` typeguard usage
import { isString } from "lodash"
let name: string | undefined = "John"
// `name` is of type `string | undefined`
let price: number | undefined = 1
// `price` is of type `number | undefined`
if (isString(name)) {
name
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-10.ts
Last active December 10, 2021 10:04
TypeScript Discriminated Unions
type UUID = string;
interface BasicUser {
id: UUID;
first_name: string;
last_name: string;
}
interface User extends BasicUser {
plan: 'free'
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-11.ts
Created November 29, 2021 11:15
TypeScript Discriminated Unions on destructured properties
type UserArg = PremiumUser | USer
function processUSer({ plan, premiumOptions }: UserArg) {
if (plan === "premium") {
premiumOptions
// `premiumOptions` is of type `PremiumOptions`
} else {
premiumOptions
// `premiumOptions` is of type `undefined`
}
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-12.ts
Created November 29, 2021 11:18
TypeScript Discriminated Unions with Template String types
interface Success {
type: `${string}Success`;
body: string;
}
interface Error {
type: `${string}Error`;
message: string;
}
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-13.ts
Created November 29, 2021 11:21
TypeScript TSConfig intro example
function isPremiumUser(user: User | PremiumUser): user is PremiumUser {
return user.plan === "premium"
}
let user: PremiumUser | User | undefined
// the line below should raise a TypeScript error,
// but it doesn't!
if (isPremiumUser(user)) {
// ...
@charlypoly
charlypoly / retool-typescript-control-flow-analysis-14.ts
Created November 29, 2021 11:28
TypeScript Force checking index accesses (1)
let myPrices: number[] = [1, 2.4, 2.0]
const defaultPrice = myPrices[40]
// `defaultPrice` is of type `number`