Values in TypeScript
Our first example will demonstrate various value types in TypeScript including strings, numbers, and booleans. Here’s the full source code:
// Strings, which can be concatenated with +
console.log("Type" + "Script")
// Numbers (TypeScript doesn't distinguish between integers and floats)
console.log("1+1 =", 1 + 1)
console.log("7.0/3.0 =", 7.0 / 3.0)
// Booleans, with boolean operators as you'd expect
console.log(true && false)
console.log(true || false)
console.log(!true)
To run the program, save it as values.ts
and use ts-node
(assuming you have TypeScript and ts-node installed):
$ ts-node values.ts
TypeScript
1+1 = 2
7.0/3.0 = 2.3333333333333335
false
true
false
TypeScript is a statically typed superset of JavaScript, so it shares many characteristics with JavaScript. Unlike some other languages, TypeScript (and JavaScript) use a single number type for both integers and floating-point numbers.
TypeScript also provides type inference, meaning you don’t always have to explicitly declare types. However, you can add type annotations for clarity:
let language: string = "TypeScript"
let version: number = 4.5
let isAwesome: boolean = true
These examples demonstrate basic value types in TypeScript. As you progress, you’ll encounter more complex types and structures that TypeScript offers.