Your First TypeScript Code
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 3 of 73.
Now it's time to write your first TypeScript code! The key difference between TypeScript and JavaScript is the ability to add type annotations to your variables.
A type annotation tells TypeScript exactly what kind of data a variable should hold. The syntax is simple: you add a colon followed by the type name after the variable name.
let variableName: type = value;For example, to create a variable that can only hold text (strings), you would write:
let message: string = "Hello, World!";The : string part is the type annotation. It explicitly tells TypeScript that message should only contain string values.
If you try to assign a number or any other type to this variable later, TypeScript will catch the error before your code runs.
This explicit typing is what makes TypeScript so powerful for catching bugs early and making your code more predictable.
Challenge
EasyCreate a variable named greeting with an explicit type annotation of string and assign it the value "Hello, TypeScript!".
Then, print the variable to the console using console.log().
Try it yourself
// TODO: Write your code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples