Type Annotation / Type Inference
| Since: | TypeScript 1.0(2014) |
|---|
Type annotations let you attach type information to variables and functions, while type inference lets TypeScript determine types automatically. Using both effectively helps you write concise, safe code.
Syntax
let variableName: type = value;
// Type annotations for function parameters and return value
function functionName(param: type, param: type): returnType {
return value;
}
// Type inference: the type is determined automatically from the initial value (no annotation needed).
let variableName = value; // The type of the value becomes the type of the variable.
Syntax List
| Syntax | Description |
|---|---|
| : type | Annotation syntax for specifying the type of a variable, parameter, or return value. Write the type name after the colon. |
| Type inference | A mechanism where TypeScript automatically determines the type from an initial value or expression result. Allows you to omit explicit annotations. |
| Return type inference | TypeScript automatically infers the return type of a function from its return statement. Allows you to omit an explicit return type annotation. |
| Type assertion (as) | Used when you as the programmer know more specific type information than TypeScript can infer. Similar in concept to a cast. |
Sample Code
let userName: string = "Yagami Iori";
let age: number = 20;
let isActive: boolean = true;
// Type inference: the annotation can be omitted when an initial value is provided.
let city = "New York"; // Inferred as type string.
let score = 95; // Inferred as type number.
// score = "excellent"; // Error: score is type number, so a string cannot be assigned.
// Function type annotations: explicitly specify parameter and return types.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(3, 5)); // Outputs 8.
// Return type inference: the type is determined automatically from the return statement.
function greet(name: string) { // Return type is automatically inferred as string.
return `Hello, ${name}!`;
}
console.log(greet("Kusanagi Kyo")); // Outputs "Hello, Kusanagi Kyo!".
// Type annotation on an arrow function.
const multiply = (x: number, y: number): number => x * y;
console.log(multiply(4, 6)); // Outputs 24.
// Type assertion (as): specify a more concrete type explicitly.
// const input = document.getElementById("name") as HTMLInputElement; // Browser environment only
// input is treated as HTMLInputElement rather than HTMLElement.
// Type annotation on an object literal.
let product: { name: string; price: number } = {
name: "Introduction to Programming",
price: 2800,
};
console.log(`${product.name}: $${product.price}`);
// Outputs "Introduction to Programming: $2800".
Running the above produces the following output:
npx ts-node ts_type_annotation.ts 8 Hello, Kusanagi Kyo! 24 Introduction to Programming: $2800
Details
A type annotation attaches type information to a variable, parameter, or return value using the : typeName syntax. This allows TypeScript to detect type mismatches at compile time, and also enables editor autocompletion and serves as inline documentation.
Type inference is the mechanism by which TypeScript automatically determines the type from context. Writing let count = 0; is enough for TypeScript to treat count as number, so no annotation is needed. As a general style guideline, rely on inference when the type is obvious from the initial value, and write an explicit annotation when the type is not clear — such as for function parameters or variables declared without an initial value.
Note: Type assertions (as) forcibly override TypeScript's type system. Specifying the wrong type can lead to runtime errors. Use them only when you are certain about the type.
If you find any errors or copyright issues, please contact us.