TypeScript: Type Syntax
Type Declaration Syntax
The first thing you shoud do is add types to function parameters. This is the most simple, useful.
examples
const f_vec_length = ((v: number[]) => Math.hypot(...v));
// vector addition const f_vec_add = (( [a1, a2]: [number, number], [b1, b2]: [number, number], ): [number, number] => [a1 + b1, a2 + b2]);
in general, the form is:
:TypeSpec
typically placed after a variable name.
Type Syntax
here are the syntax for the type spec.
Basic Type Spec Syntax for JavaScript Primitives
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.
Define Your Own Named Type
you can define your own named type.
there are two ways, one is by defining a type alias and the other way is to define a interface.
Type Alias
type TypeName = TypeSpec
example
// define a named type. either a number or string type NumOrStr = number | string;
// define a named type. a object that represent coordinate of a point type Point = { x: number; y: number; };
Interface
interface TypeName = TypeSpec
example
// define a named type. a object that represent coordinate of a point interface Point = { x: number; y: number; };
What's the Difference Between “type” and “interface”
basically, a interface type spec can be extended later in a different place.
For beginners, you don't need to worry about them. Use either.
Type Assertions (like “casting” type)
sometimes you need to force the type spec of a value from one to another. (normally, type spec is specified for a variable. here, it's for a value, often the value of a variable.)
two syntax for this:
<TypeSpec> val
- val
as TypeSpec
example
const xx = ((<HTMLInputElement> searchBox).value)
const xx = ((searchBox as HTMLInputElement).value);
this usually happen with DOM objects. because DOM was not well designed some decade ago before TypeScript.