Created
June 14, 2018 00:19
-
-
Save mathewbyrne/12cce952f0d0091f209abf9a7120dbf6 to your computer and use it in GitHub Desktop.
This file contains 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 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