An Introduction to TypeScript Types

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static types to JavaScript, which can help improve code reliability and readability.

TypeScript has several built-in types that you can use to declare variables in your code. These types include:

  • any: A type that represents any value. This is the default type if no other type is specified.
  • unknown: A type that represents a value that is not known. This is similar to the any type, but it provides more type safety.
  • boolean: A type that can be either true or false.
  • number: A numeric type that can represent both integer and floating-point values.
  • string: A sequence of Unicode characters.
  • symbol: A unique and immutable data type that can be used as an identifier for object properties.
  • undefined: A type that represents a value that has not been assigned a value.
  • null: A type that represents a null value.
  • void: A type that represents the absence of a value. This is typically used for functions that do not return a value.

In addition to these built-in types, you can also create your own custom types in TypeScript using interfaces, classes, and enums.

Here's an example of how you can use types in TypeScript:

function greet(name: string) {
console.log("Hello, " + name);
}
greet("John"); // Output: "Hello, John"

In this code, the greet function is declared with a parameter name that is of type string. This means that the greet function expects to receive a string as an argument when it is called. If you try to call the greet function with a value that is not a string, you will get an error at compile time.

Overall, TypeScript's built-in types and support for custom types can help make your code more reliable and easier to understand.


November 28, 2022
49