Skip to content

Instantly share code, notes, and snippets.

@mathewbyrne
Created June 14, 2018 00:19
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 mathewbyrne/12cce952f0d0091f209abf9a7120dbf6 to your computer and use it in GitHub Desktop.
Save mathewbyrne/12cce952f0d0091f209abf9a7120dbf6 to your computer and use it in GitHub Desktop.
interface User {
name: string,
id: number,
avatar?: string,
}
const user: User = {
name: 'Testing',
id: 1234,
avatar: 'http://example.com/foo.jpg',
}
// Union types
interface NewUser {
name: string,
id: number
avatar?: {
url: string,
width: number,
height: number
}
}
const getAvatarUrl = (user: User | NewUser): string => {
if (typeof user.avatar == 'string') {
return user.avatar;
} else if (typeof user.avatar == 'object') {
return user.avatar.url;
}
return 'http://example.com/';
}
// Intersection Types
interface StylingProps {
variations?: string[],
}
interface AccessibilityProps {
title?: string,
alt?: string,
}
type MyComponent = StylingProps & AccessibilityProps & {
count: number
}
// Enums and Type Aliases
type Currency = string;
const USD: Currency = 'USD';
const Schmeckles: Currency = 'SCH';
/*const*/ enum BetterCurrency {
USD = 'USD',
Schmeckles = 'SCH',
}
const Foo = BetterCurrency.Schmeckles;
const BetterCurrencyName: { [key in BetterCurrency]: string } = {
[BetterCurrency.USD]: 'US Dollars',
[BetterCurrency.Schmeckles]: 'Schmeckles',
}
console.log(BetterCurrencyName['SCH'])
// Mapped Types
interface Invoice {
id: string,
amount: number,
}
type PartialInvoice = Partial<Invoice>;
const i1: PartialInvoice = { amount: 1234 }
type ReadonlyInvoice = Readonly<Invoice>
const i2: ReadonlyInvoice = { id: 'QWERTY', amount: 1234 }
// i2.id = 'Foo'
type InvoiceAmount = Pick<Invoice, 'amount'>
const i3: InvoiceAmount = { amount: 1234 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment