typia
Version:
Superfast runtime validators with only one line
103 lines (100 loc) • 3.95 kB
JavaScript
import ts from 'typescript';
var TypeFactory;
(function (TypeFactory) {
TypeFactory.isFunction = (type) => TypeFactory.getFunction(type) !== null;
TypeFactory.getFunction = (type) => {
const node = type.symbol?.declarations?.[0];
if (node === undefined)
return null;
return ts.isFunctionLike(node)
? node
: ts.isPropertyAssignment(node) || ts.isPropertyDeclaration(node)
? ts.isFunctionLike(node.initializer)
? node.initializer
: null
: null;
};
TypeFactory.getReturnTypeOfClassMethod = (props) => {
// FIND TO-JSON METHOD
const symbol = props.class.getProperty(props.function);
if (!symbol)
return null;
else if (!symbol.valueDeclaration)
return null;
// GET FUNCTION DECLARATION
const functor = props.checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);
// RETURNS THE RETURN-TYPE
const signature = props.checker.getSignaturesOfType(functor, ts.SignatureKind.Call)[0];
return signature ? signature.getReturnType() : null;
};
TypeFactory.getFullName = (props) => {
// PRIMITIVE
const symbol = props.symbol ?? props.type.aliasSymbol ?? props.type.getSymbol();
if (symbol === undefined)
return props.checker.typeToString(props.type);
// UNION OR INTERSECT
if (props.type.aliasSymbol === undefined &&
props.type.isUnionOrIntersection()) {
const joiner = props.type.isIntersection() ? " & " : " | ";
return props.type.types
.map((child) => TypeFactory.getFullName({
checker: props.checker,
type: child,
}))
.join(joiner);
}
//----
// SPECIALIZATION
//----
const name = get_name(symbol);
// CHECK GENERIC
const generic = props.type.aliasSymbol && props.aliasTypeArguments !== false
? (props.type.aliasTypeArguments ?? [])
: props.checker.getTypeArguments(props.type);
return generic.length
? name === "Promise"
? TypeFactory.getFullName({
checker: props.checker,
type: generic[0],
})
: `${name}<${generic
.map((child) => TypeFactory.getFullName({
checker: props.checker,
type: child,
}))
.join(", ")}>`
: name;
};
const explore_name = (props) => ts.isModuleBlock(props.node)
? explore_name({
node: props.node.parent.parent,
name: `${props.node.parent.name.getFullText().trim()}.${props.name}`,
})
: props.name;
const get_name = (symbol) => {
const parent = symbol.getDeclarations()?.[0]?.parent;
return parent
? explore_name({
node: parent,
name: symbol.escapedName.toString(),
})
: "__type";
};
TypeFactory.keyword = (type) => {
return ts.factory.createKeywordTypeNode(type === "void"
? ts.SyntaxKind.VoidKeyword
: type === "any"
? ts.SyntaxKind.AnyKeyword
: type === "unknown"
? ts.SyntaxKind.UnknownKeyword
: type === "boolean"
? ts.SyntaxKind.BooleanKeyword
: type === "number"
? ts.SyntaxKind.NumberKeyword
: type === "bigint"
? ts.SyntaxKind.BigIntKeyword
: ts.SyntaxKind.StringKeyword);
};
})(TypeFactory || (TypeFactory = {}));
export { TypeFactory };
//# sourceMappingURL=TypeFactory.mjs.map