Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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