Skip to content

Instantly share code, notes, and snippets.

@dkundel
Created June 13, 2019 19:29
Show Gist options
  • Save dkundel/ecd2d0a02c19b0c7349b66412fb7777d to your computer and use it in GitHub Desktop.
Save dkundel/ecd2d0a02c19b0c7349b66412fb7777d to your computer and use it in GitHub Desktop.
Examples from AngularSF TypeScript talk
/** Types vs Interfaces */
type Configuration = {
baseUrl: string;
ttl: number;
};
type ConfigWithCredentials = Configuration & {
credentials: {
username: string;
};
};
const config: ConfigWithCredentials = {
baseUrl: 'https://dkundel.com',
ttl: 3600,
credentials: {
username: 'dom',
},
};
interface Animal {
sleep(): void;
}
interface Fish extends Animal {
swim(): void;
}
class Goldfish implements Fish {
sleep = () => {};
swim = () => {};
}
/** keyof */
type ConfigurationKeys = keyof Configuration;
function set<T extends ConfigurationKeys>(
key: T,
value: Configuration[T]
): void {
console.log(`Setting: ${key} to ${value}`);
}
set('baseUrl', 'https://twitter.com');
set('ttl', 22);
set('baseUrl', true);
/** mapped types */
type ConfigurationLastUpdated = { [K in ConfigurationKeys]: Date };
const updates: ConfigurationLastUpdated = {
baseUrl: new Date(),
ttl: new Date(),
};
/** conditional types */
type SafeDataJson<T> = T extends (infer U)[]
? { data: U[] }
: T extends object
? T
: { data: [T] };
type Example = SafeDataJson<{ hello: true }>;
type Example2 = SafeDataJson<[1, 2, 3]>;
type Example3 = SafeDataJson<'bye'>;
/** object vs Object */
const hello: Object = 'hello';
const bye: object = 'bye';
const actuallyBye: object = { bye: true };
Object.create('hello');
/** unknown */
function parseNumber(value: unknown): number {
if (typeof value === 'number') {
return value;
}
if (typeof value === 'string') {
return parseInt(value);
}
return NaN;
}
const apiValue: unknown = '12';
const parsedValue: number = parseNumber(apiValue);
/** never */
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? K : never
}[keyof T];
type Demo = FunctionPropertyNames<{
foo: () => {};
bar: () => true;
}>;
type Status = 'success' | 'failure' | 'pending';
function throwNonExhaustive(value: never): never {
throw new Error('Should not reach this');
}
function isDone(value: Status): boolean {
switch (value) {
case 'success':
case 'failure':
return true;
case 'pending':
return false;
default:
return throwNonExhaustive(value);
}
}
isDone('pending');
/** type-fest */
import { JsonObject } from 'type-fest';
const data: JsonObject = {
success: true,
lastUpdate: new Date(),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment