eslint-plugin-complete
Version:
An ESLint plugin that contains useful rules.
77 lines (76 loc) • 2.59 kB
JavaScript
// Some of the functions are copy-pasted here from the `typescript-eslint` repository and slightly
// modified.
import ts from "typescript";
/** Gets all of the type flags in a type, iterating through unions automatically. */
function getTypeFlags(type) {
let flags = 0;
for (const t of unionTypeParts(type)) {
flags |= t.flags;
}
return flags;
}
export function getTypeName(type) {
const escapedName = type.getSymbol()?.escapedName;
if (escapedName !== undefined && escapedName !== "__type") {
return escapedName;
}
const aliasSymbolName = type.aliasSymbol?.getName();
if (aliasSymbolName !== undefined) {
return aliasSymbolName;
}
// The above checks do not work with boolean values.
if ("intrinsicName" in type) {
const { intrinsicName } = type;
if (typeof intrinsicName === "string" && intrinsicName !== "") {
return intrinsicName;
}
}
return undefined;
}
/**
* @param symbol The symbol to check.
* @param flagsToCheck The composition of one or more `ts.SymbolFlags`.
*/
export function isSymbolFlagSet(symbol, flagsToCheck) {
return isFlagSet(symbol.flags, flagsToCheck);
}
/**
* Checks if the given type is either an array/tuple type, or a union made up solely of array/tuple
* types.
*
* Based on the `isTypeArrayTypeOrUnionOfArrayTypes` from `typescript-eslint`, but modified to also
* match tuples.
*/
export function isTypeArrayTupleTypeOrUnionOfArrayTupleTypes(type, checker) {
for (const t of unionTypeParts(type)) {
if (!checker.isArrayType(t) && !checker.isTupleType(t)) {
return false;
}
}
return true;
}
export function isAny(type) {
return isTypeFlagSet(type, ts.TypeFlags.Any);
}
/** Returns all types of a union type or an array containing `type` itself if it's no union type. */
export function unionTypeParts(type) {
return isUnion(type) ? type.types : [type];
}
function isUnion(type) {
// We cannot use the `isTypeFlagSet` function here, since that decomposes unions.
return isFlagSet(type.flags, ts.TypeFlags.Union);
}
/**
* Note that if the type is a union, this function will decompose it into the parts and get the
* flags of every union constituent.
*
* @param type The type to check.
* @param flagsToCheck The composition of one or more `ts.TypeFlags`.
*/
export function isTypeFlagSet(type, flagsToCheck) {
const flags = getTypeFlags(type);
return isFlagSet(flags, flagsToCheck);
}
export function isFlagSet(flags, flag) {
return (flags & flag) !== 0;
}