TypeScript Basics: Type Syntax Is Consistent
Welcome to the Type Syntax Is Consistent lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
TypeScript's syntax for types doesn't change from place to place. Every type can be used anywhere that types are allowed. For example, we know that
stringcan be the type of a variable, a function argument, or a function's return value.>
const aString: string = 'hello';aString;Result:
>
function takesString(aString: string) {return aString;}takesString('this is returned');Result:
>
function returnsString(): string {return 'hello';}returnsString();Result:
'hello'
We know that a variable can be an array of strings. That tells us that we can also use an "array of strings" type for function arguments and function return values.
>
const arrayOfStrings: string[] = ['hello', 'world'];arrayOfStrings;Result:
Here's a code problem:
Give this function's argument a type that means "an array of strings".
function takesAnArrayOfStrings(anArrayOfStrings: string[]) {return anArrayOfStrings;}takesAnArrayOfStrings(['hello', 'world']);- Goal:
['hello', 'world']
- Yours:
['hello', 'world']
Because the type syntax doesn't change from place to place, we can guess at the structure of more complex types. If we can make an array of
strings, we should be able to make arrays of any type.For example, we can make an array of arrays of strings. (That is: each element of the array is itself an array of strings.)
>
const arrayOfArraysOfStrings: (string[])[] = [['hello'], ['world']];arrayOfArraysOfStrings;Result:
We added parentheses in that type to clarify that the things inside the array have the type
string[]. But those parentheses aren't necessary and are rarely used in real-world TypeScript code. The type in the next example means the same thing.>
const arrayOfArraysOfStrings: string[][] = [['hello'], ['world']];arrayOfArraysOfStrings;Result:
Here's a code problem:
Give this function a return type that means "an array of arrays of strings".
function returnsAnArrayOfArraysOfStrings(): string[][] {const array = [];array.push(['hello']);array.push(['world']);return array;}const array = returnsAnArrayOfArraysOfStrings();array;- Goal:
[['hello'], ['world']]
- Yours:
[['hello'], ['world']]
Every type works everywhere:
- As a variable.
- As a function argument or return type.
- Inside an array.
- As an object property.
- Etc.