TypeScript: Type Syntax
Type Declaration Syntax
- The first thing you shoud do is add types to function parameters.
- This is the most simple, useful.
the form is:
:TypeSpec
placed after a variable name.
Example
// vector addition const f_vec_add = (( [a1, a2]: [number, number], [b1, b2]: [number, number], ): [number, number] => [a1 + b1, a2 + b2]);
const f_vec_length = ((v: number[]) => Math.hypot(...v));
Type Syntax
here are the syntax for the type spec.
Type Spec Syntax for JavaScript Primitive Types
string
number
boolean
any
Array Type
TypeSpec[]
Object Type
{ …: TypeSpec; …: TypeSpec … }
Optional Property
add a question mark to the end of variable name.
{ …: TypeSpec; … ?: TypeSpec })
Union Types
Union Types means one or the other.
TypeSpec | TypeSpec
can be more than two items.