isComplete: boolean = false;: This variableisCompleteis of type boolean and is initialized with the valuefalse.stock: number = 10;: This variablestockis of type number and is initialized with the value10.greeting: string = "Welcome!";: This variablegreetingis of type string and is initialized with the value"Welcome!".largeNumber: bigint = 900719925474099100n;: This variablelargeNumberis of type bigint and is initialized with a large number.unique: symbol = Symbol("unique");: This variableuniqueis of type symbol and is initialized with a unique symbol.
nothingHere: null = null;: This variablenothingHereis of type null and is assigned the valuenull.notAssigned: undefined;: This variablenotAssignedis declared but not assigned a value, hence its type isundefined.
interface Product { name: string; price: number; }: This defines an interfaceProductwithnameandpriceproperties.product: Product = { name: "Tablet", price: 500 };: This variableproductis of typeProductand represents a product object with a name and a price.colors: string[] = ["Red", "Green", "Blue"];: This variablecolorsis an array of strings initialized with colors.scores: number[] = [85, 90, 78];: This variablescoresis an array of numbers initialized with scores.
anythingGoes: unknown = 42;: This variableanythingGoesis of type unknown and is assigned the value42.neverReturns: never;: This variableneverReturnsis declared but never assigned a value, indicating it will never have a value.flexibleType: number | string;: This variableflexibleTypecan hold either a number or a string.
function calculateArea(width: number, height: number): number {
return width * height;
}- Type annotations in TypeScript allow you to explicitly specify the type of a variable.
- Primitive types include boolean, number, string, bigint, and symbol.
- Special types such as null and undefined represent absence of value and uninitialized variables, respectively.
- Structural types can be defined using interfaces to specify the structure of objects.
- Arrays in TypeScript can be defined using square brackets followed by the type of elements.
- Utility types provide additional features for working with types, such as unknown and never.
- Functions can also have type annotations for parameters and return types, ensuring type safety and clarity.