Typescript type inference

Created By: chatGPT

TypeScript is a superset of JavaScript that provides optional static typing. One of its powerful features is type inference, which allows TypeScript to automatically deduce the type of a variable or a function return value based on the context and initialization. This means you don't always need to explicitly declare types. Here are a few examples of how type inference works in TypeScript.
let message = "Hello, TypeScript!"; // inferred as string

const num = 42; // inferred as number

function add(a: number, b: number) {
    return a + b; // inferred return type as number
}

const result = add(5, 10); // result is inferred as number
Type inference is particularly useful when dealing with complex data structures or when working with functions. TypeScript can intelligently infer types even when they are nested within other structures. Below is an example with an object.
interface User {
    name: string;
    age: number;
}

const user = {
    name: "Alice",
    age: 30
}; // inferred as User

function getUserInfo(user: User) {
    return `${user.name} is ${user.age} years old.`; // inferred return as string
}

const info = getUserInfo(user); // info is inferred as string
Type inference can also occur with arrays. When you initialize an array with specific types, TypeScript can infer the type of its elements automatically.
const numbers = [1, 2, 3, 4, 5]; // inferred as number[]

const strings = ["a", "b", "c"]; // inferred as string[]

function logArray(arr: string[]) {
    arr.forEach((item) => console.log(item));
}

logArray(strings); // no type error, inferred as string[]
In addition to inferring types from initialization, TypeScript can also infer types from context like function calls or return statements. For example, if you call a function that returns a specific type, TypeScript will infer that type for the variable.
function multiply(a: number, b: number) {
    return a * b; // inferred return type as number
}

const product = multiply(6, 7); // product is inferred as number
When using generics, TypeScript uses type inference to determine the appropriate type based on usage. This allows for more flexible and reusable code.
function identity<T>(arg: T): T {
    return arg; // inferred type based on the argument passed
}

const str = identity("Hello"); // T inferred as string
const numIdentity = identity(100); // T inferred as number
Type inference not only enhances code readability but also reduces the need for excessive type annotations, making the code cleaner and more maintainable. Understanding how to leverage type inference effectively will lead to more robust and error-free TypeScript code.
Introduction And SetupVariablesData TypesAnyUnknownVoidNeverStringNumberBooleanArrayTupleEnumObjectInterfaceType AliasMethodsFunctionArrow FunctionReturn TypeParametersDefault ParametersOptional ParametersRest ParametersControl FlowIf StatementElse StatementSwitch StatementFor LoopWhile LoopDo While LoopFor...of LoopFor...in LoopBreak StatementContinue StatementFunctionsFunction OverloadingRecursive FunctionExpression FunctionOperatorsArithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsConditional (ternary) OperatorData StructuresArrayTupleObjectMapSetCommentsSingle Line CommentMulti Line CommentSyntaxType AnnotationsType InferenceNamespaceModuleExportImportDecoratorsAmbient DeclarationsEvent HandlingEvent ListenersAddEventListenerRemoveEventListenerError HandlingTry...catch StatementThrow StatementFinally BlockCustom Error TypesAsync AwaitPromisesGenericsConditional TypesMapped TypesIntersection TypesUnion TypesLiteral TypesDiscriminated UnionsType GuardsTypeof GuardInstanceof GuardAssertion FunctionsModule Augmentation