TypeScript: Define Type
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.