TypeScript Literal Inference Type
TypeScript Literal Inference Type allows you to create type annotations based on actual values, variables, or constants. This enhances type safety and code clarity by specifying that a variable can only hold specific, exact values. It's a way to express the precise values that a variable can take on, ensuring that your code is more specific and less error-prone.
Syntax:
const variableName = value as Type;
Parameters:
- variableName: The name of the variable you want to create or update.
- value: The specific value or literal you want to infer the type from.
- Type: The type you want to assign based on the value.
Example 1: In this example, TypeScript's type inference is used to create a string literal type, "red," by defining a constant variable named color
with the value "red" and creating a corresponding type, ColorType
, based on the typeof
operator.
// Define a variable 'color' and set it
// to the string literal "red" as a constant.
const color = "red" as const;
// Creating a type 'ColorType' by using
// 'typeof' on the 'color' variable.
type ColorType = typeof color;
// Printing the results to the console.
console.log(color);
Output:
red
Example 2: In this example, we have defined a custom Status
type allowing "active" or "inactive" values. The user
object with username
and status
properties ensures only valid values are assigned to status
, improving type safety and code clarity. The console.log
statements correctly display the properties with the specified type constraints.
// Defining a custom type `Status` that
// can only have the values "active" or "inactive."
type Status = "active" | "inactive";
// Creating an object `user` with
// properties `username` and `status`.
const user = {
// The `username` property is a string.
username: "GFG1",
// The `status` property is inferred as a string
// literal "active" due to the `as Status` assertion.
status: "active" as Status,
};
console.log(`Username: ${user.username}`);
console.log(`Status: ${user.status}`);
Output:
Username: GFG1
Status: active