Skip to content

Instantly share code, notes, and snippets.

@carlrip
carlrip / index.ts
Created December 17, 2019 18:23
const assertions - literals
function logStatus(status: "LOADING" | "LOADED") {
console.log(status);
}
const Status = {
Loading: "LOADING",
Loaded: "LOADED",
};
logStatus(Status.Loading); // 💥 - Type error - Argument of type 'string' is not assignable to parameter of type '"LOADING" | "LOADED"'
@carlrip
carlrip / index.ts
Created December 17, 2019 18:22
const assertions - array
type Person = {
id: number;
name: string;
scores: number[];
}
const people: Person[] = [
{ id: 1, name: "Bob", scores: [50, 45] },
{ id: 2, name: "Jane", scores: [70, 60] },
{ id: 3, name: "Paul", scores: [40, 75] }
]
@carlrip
carlrip / index.ts
Created December 17, 2019 18:20
const assertions - action object
function createGetPersonAction() {
return { type: 'GetPerson' } as const;
}
const getPersonAction = createGetPersonAction(); // `getPersonAction` is of type `{ readonly type: "GetPerson"; }`
@carlrip
carlrip / index.ts
Created December 17, 2019 18:18
ReadonlyArray generic type
type Person = {
readonly name: string;
readonly scores: ReadonlyArray<number>; // same as readonly number[]
}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:17
Readonly arrays
type Person = {
readonly name: string;
readonly scores: readonly number[];
}
const bob: Person = {
name: "Bob",
scores: [50, 45]
}
bob.scores.push(60); // 💥 - Type error - Property 'push' does not exist on type 'readonly number[]'
@carlrip
carlrip / index.ts
Created December 17, 2019 18:17
Readonly arrays - non readonly array
type Person = {
readonly name: string;
readonly scores: number[];
}
const bob: Person = {
name: "Bob",
scores: [50, 45]
}
bob.scores.push(60); // does this raise a type error?
@carlrip
carlrip / index.ts
Created December 17, 2019 18:13
The unknown type
const person: unknown = await getPerson(id);
if (isPersonWithAddress(person)) {
const postcode = person.address.postcode;
}
function isPersonWithAddress(person: any): person is Person {
return "address" in person && "postcode" in person.address;
}
@carlrip
carlrip / index.ts
Created December 17, 2019 18:11
The unknown type - using any
const person: any = await getPerson(id);
const postcode = person.address.postcode; // TypeScript doesn't yell at us but what if there is no address property ... 💥!
@carlrip
carlrip / app.js
Created October 29, 2019 05:08
React useState
const [state, setState] = useState(initialState);
@carlrip
carlrip / Counter.tsx
Created September 19, 2019 03:53
Reset type
type Reset = {
type: "reset";
to: number;
};
type Actions = Increment | Decrement | Reset;