Skip to content

Instantly share code, notes, and snippets.

@szhu
Last active October 6, 2021 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szhu/54a314fa055b4e6d07e1446ca9f3ea8a to your computer and use it in GitHub Desktop.
Save szhu/54a314fa055b4e6d07e1446ca9f3ea8a to your computer and use it in GitHub Desktop.
// pbpaste | deno run --reload https://gist.githubusercontent.com/szhu/54a314fa055b4e6d07e1446ca9f3ea8a/raw/convertPropTypesToTs.ts | pbcopy
interface ToStringAble {
toString(): string;
}
type TypeSpecToString = (this: TypeSpec) => string;
interface TypeSpec {
name: string;
optional: boolean;
toString: TypeSpecToString;
}
const Type = (name: string, toString: TypeSpecToString) =>
({
name,
optional: true,
toString,
isRequired: {
name,
optional: false,
toString,
} as TypeSpec,
} as TypeSpec & { isRequired: TypeSpec });
function Name(this: TypeSpec) {
return this.name;
}
const PropTypes = {
node: Type("React.ReactNode", Name),
element: Type("Element", Name),
bool: Type("boolean", Name),
number: Type("number", Name),
string: Type("string", Name),
object: Type("{}", Name),
array: Type("unknown[]", Name),
func: Type("() => void", Name),
any: Type("any", Name),
shape: (contents: { [key: string]: TypeSpec }) =>
Type("object", function () {
let result = "{\n";
for (let key in contents) {
let value = contents[key];
let q = (value && value.optional) ? "?" : "";
result += `${key}${q}: ${value},\n`;
}
result += "}";
return result;
}),
arrayOf: (contents: ToStringAble[]) =>
Type("array", function () {
return `(${contents.toString()})[]`;
}),
oneOfType: (contents: ToStringAble[]) =>
Type("union", function () {
return "(" + contents.map((item) => item.toString()).join(" | ") + ")";
}),
oneOf: (contents: ToStringAble[]) =>
Type("stringEnum", function () {
return (
"(" + contents.map((item) => JSON.stringify(item)).join(" | ") + ")"
);
}),
instanceOf: (contents: string) =>
Type("instanceOf", function () {
return contents;
}),
};
let stdin = new TextDecoder().decode(await Deno.readAll(Deno.stdin));
stdin = stdin.trim();
stdin = stdin.replace(/(\w+)Shape/g, '"$1"');
if (stdin.startsWith("{")) {
stdin = "PropTypes.shape(" + stdin + ")";
}
const input = eval(stdin);
console.log(input.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment