Skip to content

Instantly share code, notes, and snippets.

View janjakubnanista's full-sized avatar

Ján Jakub Naništa janjakubnanista

  • LayerZero
  • Vancouver
View GitHub Profile
@janjakubnanista
janjakubnanista / 001-simple.ts
Last active May 22, 2020 14:24
Checking for strings and numbers in TypeScript
// You can easily extend this example to check for
// number, boolean, bigint, Function and symbol types
const isString = (value: unknown): value is string => typeof value === 'string';
@janjakubnanista
janjakubnanista / 002-interface.ts
Last active May 31, 2020 18:29
TypeScript type guards for an interface
// In this made up scenario we are trying to make sure we didn't get
// a corrupted piece of data from a WebSocket
interface WebSocketMessage {
time: number;
text: string;
description?: string;
content: string[];
}
// You could also write this as one looong if statement if you prefer
@janjakubnanista
janjakubnanista / 003-ts-type-checked.ts
Created May 22, 2020 15:04
TypeScript type guards using ts-type-checked
import { isA, typeCheckFor } from 'ts-type-checked';
// Using the typeCheckFor type guard factory
const isString = typeCheckFor<string>();
const isWebSocketMessage = typeCheckFor<WebSocketMessage>();
// Or directly checking a value somewhere in the code
if (isA<string>(value)) return 'Hello String';
if (isA<WebSocketMessage>(value)) return 'Hello Web Socket!';
@janjakubnanista
janjakubnanista / articles.001.001.start.tsx
Last active June 6, 2020 12:57
Generic function component 1: props
export interface SelectProps<T> {
// The list of items
items: T[];
// The selected item
value?: T;
// And our change handler
onChange: (value: T) => void;
}
// Attempt 1: Add generic props to React.FC type
//
// TypeScript will not allow a const to be generic like this!
export const Select: React.FC<SelectProps<T>> = props => {
// Oh no!
}
// Attempt 2: Make the component function generic
//
// JSX parser will colide with TypeScript when trying to do something like this
export function Select<T>(props: SelectProps<T>) {
// It works!
}
export function Select<T>(props: SelectProps<T>) {
// This should not be allowed for React components!
return Promise.resolve(null);
}
// And we don't get a warning when defining defaultProps either :/
Select.defaultProps = 7;
// Approach 1: the easy way out
//
// We can just define the return type of our Select
// and make sure it matches the return type of React.FC
function Select<T>(props: SelectProps<T>): React.ReactElement | null {
return null;
}
// Approach 2: diving back in looking for a better way
//
export function Select<T>({ items }: SelectProps<T>) {
return <div>
{items.map(item => {
const selected = /* We now need to know how to check whether this item is the selected one */;
return <div key={/* We will also need to get a unique identifier from the type T */}/>;
})}
</div>;
}
export interface SelectProps<T> {
// ... Previous props
idFromValue: (value: T) => string | number;
}