TypeScript Literal Inference Type
Last Updated :
09 Nov, 2023
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.
Javascript
const color = "red" as const;
type ColorType = typeof color;
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.
Javascript
type Status = "active" | "inactive" ;
const user = {
username: "GFG1" ,
status: "active" as Status,
};
console.log(`Username: ${user.username}`);
console.log(`Status: ${user.status}`);
|
Output:
Username: GFG1
Status: active
Share your thoughts in the comments
Please Login to comment...