Skip to content

Instantly share code, notes, and snippets.

@christianscott
Created January 16, 2019 05:09
Show Gist options
  • Save christianscott/8c1724eea13d31bd5c5776864c71a5b3 to your computer and use it in GitHub Desktop.
Save christianscott/8c1724eea13d31bd5c5776864c71a5b3 to your computer and use it in GitHub Desktop.
import { Preconditions, UnreachableError } from 'base/preconditions';
export module FormFieldValue {
export const enum Type {
Text,
Select,
OnOff,
Numeric,
}
function getNameForType(type: Type): string {
switch (type) {
case Type.Text:
return 'string';
case Type.Select:
return 'string or undefined';
case Type.OnOff:
return 'boolean';
case Type.Numeric:
return 'number';
default:
throw new UnreachableError(type);
}
}
export type Text = { type: Type.Text; value: string };
export type Numeric = { type: Type.Numeric; value: number };
export type OnOff = { type: Type.OnOff; value: boolean };
export type Select = { type: Type.Select; value: string | undefined };
export type T = Text | Numeric | OnOff | Select;
export type Primitive = T['value'];
export function text(value: string): Text {
return { type: Type.Text, value };
}
export function onOff(value: boolean): OnOff {
return { type: Type.OnOff, value };
}
export function numeric(value: number): Numeric {
return { type: Type.Numeric, value };
}
export function select(value: string | undefined): Select {
return { type: Type.Select, value };
}
export type PrimitiveForType<DesiredType extends Type> = Extract<T, { type: DesiredType }>['value'];
export function getAsType<DesiredType extends Type>(
formFieldValue: T,
type: DesiredType,
): PrimitiveForType<DesiredType> {
Preconditions.checkArgument(
formFieldValue.type === type,
`Expected field value of type ${
getNameForType(type)
}, got field value of type ${
getNameForType(formFieldValue.type)
}. You probably have two form fields with the same label.`,
);
return formFieldValue.value;
}
export function getDefaultValue(type: Type) {
switch (type) {
case Type.Numeric:
return 0;
case Type.OnOff:
return false;
case Type.Select:
return undefined;
case Type.Text:
return '';
default:
throw new UnreachableError(type);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment