Types
cvxVariants
Extracts the properties of the first argument of a given function type variants.
Syntax
type cvxVariants<T extends (...keys: any) => any> = Omit<Undefined<Parameters<T>[0]>, ExcludeKeys>;
import { cvx, type cvxVariants } from "xuxi";
const classes = cvx({
assign: "flex items-center justify-center",
variants: {
weight: {
light: "font-light",
bold: "font-bold",
semibold: "font-semibold"
},
color: {
blue: "text-blue-600",
green: "text-green-700",
red: "text-red-500",
purple: "text-purple-500"
},
size: {
sm: "h-4",
md: "h-6",
lg: "h-10",
xl: "h-14"
}
}
});
type VariantsType = cvxVariants<typeof classes>;
// Output:
// type VariantsType = {
// weight?: "bold" | "light" | "semibold" | undefined;
// color?: "blue" | "green" | "red" | "purple" | undefined;
// size?: "sm" | "md" | "lg" | "xl" | undefined;
// };
type Color = NonNullable<cvxVariants<typeof classes>["color"]>;
// type Color = "blue" | "green" | "red" | "purple";
InferType
InferType<T>
is a utility type that extracts the return type of a given function type. It simplifies type inference, making it easier to work with dynamically typed functions without manually specifying return types.
This is especially useful in scenarios where functions are passed as generics, allowing for better type safety and code maintainability.
Syntax
type InferType<T> = T extends (...args: any[]) => infer R ? R : never;
How InferType Works
- If
T
is a function type, it extracts and returns the function’s return type (R
). - If
T
is not a function, it resolves tonever
, preventing invalid type inference. - It utilizes TypeScript’s conditional types along with the
infer
keyword to dynamically deduce the return type from any given function type.
Example Usage
// Example 1: Extracting return type from a function
function getNumber(): number {
return 42;
}
type Result = InferType<typeof getNumber>;
// Result is inferred as `number`
// Example 2: Inferring return type from a function type
type MyFunction = () => string;
type Extracted = InferType<MyFunction>;
// Extracted is `string`
// Example 3: Handling functions with parameters
type Multiply = (a: number, b: number) => number;
type Output = InferType<Multiply>;
// Output is `number`
// Example 4: Non-function types resolve to `never`
type NotAFunction = string;
type InvalidExtraction = InferType<NotAFunction>;
// InvalidExtraction is `never`
When to Use InferType
- When working with generic functions and needing to extract their return types dynamically.
- When dealing with higher-order functions that take functions as arguments and return other functions.
- When building utility types that rely on function type inference to ensure type consistency.