mirror of
https://github.com/gristlabs/grist-core.git
synced 2026-03-02 04:09:24 +00:00
(core) move home server into core
Summary: This moves enough server material into core to run a home server. The data engine is not yet incorporated (though in manual testing it works when ported). Test Plan: existing tests pass Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D2552
This commit is contained in:
38
app/common/StringUnion.ts
Normal file
38
app/common/StringUnion.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* TypeScript will infer a string union type from the literal values passed to
|
||||
* this function. Without `extends string`, it would instead generalize them
|
||||
* to the common string type.
|
||||
*
|
||||
* Example definition:
|
||||
* const Race = StringUnion(
|
||||
* "orc",
|
||||
* "human",
|
||||
* "night elf",
|
||||
* "undead",
|
||||
* );
|
||||
* type Race = typeof Race.type;
|
||||
*
|
||||
* For more details, see:
|
||||
* https://stackoverflow.com/questions/36836011/checking-validity-of-string
|
||||
* -literal-union-type-at-runtime?answertab=active#tab-top
|
||||
*/
|
||||
export const StringUnion = <UnionType extends string>(...values: UnionType[]) => {
|
||||
Object.freeze(values);
|
||||
const valueSet: Set<string> = new Set(values);
|
||||
|
||||
const guard = (value: string): value is UnionType => {
|
||||
return valueSet.has(value);
|
||||
};
|
||||
|
||||
const check = (value: string): UnionType => {
|
||||
if (!guard(value)) {
|
||||
const actual = JSON.stringify(value);
|
||||
const expected = values.map(s => JSON.stringify(s)).join(' | ');
|
||||
throw new TypeError(`Value '${actual}' is not assignable to type '${expected}'.`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const unionNamespace = {guard, check, values};
|
||||
return Object.freeze(unionNamespace as typeof unionNamespace & {type: UnionType});
|
||||
};
|
||||
Reference in New Issue
Block a user