Exploring TypeScript Type Annotations – Data Types
This post was originally posted on GitHub by the WowBar team
Author: zhilidali
Welcome to the Exploring TypeScript Type Annotations tutorial series. Starting with a (new) look at TypeScript, this article explores TypeScript’s native data types.
directory
- First look at type annotations
- The base type
- JS base type
- New Base Type
- Base type compatibility
- Reference types
- object
- Array
- Tuple
- Enum
- Date RegExp Error
- Function
- Class
- conclusion
First look at type annotations
let bar: boolean = 'TS'; // Error: Type 'string' is not assignable to type 'boolean'.ts(2322)
Copy the code
Type Annotation Type Annotation
- grammar :
: Type
. Such as: boolean
. - role: Specifies the data type of the convention variable. As agreed
bar
Is a Boolean value. - benefits :
- Check the type at static compile time. The compiler will warn when the type operation is not reasonable, such as:
Type 'string' is not assignable to type 'boolean'
. - As documentation. Move the cursor to VSCode
bar
When on, will promptlet bar: boolean
.
- Check the type at static compile time. The compiler will warn when the type operation is not reasonable, such as:
2 Basic Types
Primitive Type
- Supports basic JS types:
boolean
,number
,string
,symbol
,undefined
null
- New Base type:
void
,never
- New type:
any
,unknow
JS base type
TypeScript supports basic JavaScript types
let tsBoo: boolean = false;
let tsNum: number = 0x10;
let tsStr: string = 'TS';
let tsSym: symbol = Symbol('TS');
let tsUnInit: undefined;
let tsEmpty: null = { foo: 'Foo' }; // Error
Copy the code
TypeScript also supports literal types, and variables can only be initialized to the corresponding literal type value.
// String literal
let ts: 'TS';
// A numeric literal
let one: 1 = 'TS'; // Error
// Boolean literal
let truthy: true;
Copy the code
New Base Type
void
Void indicates that the function does not return a value (that is, it returns undefined).
function tsVoid() :void {
// No return value
}
Copy the code
never
Never indicates that a function does not return. If an exception is thrown or a generator function exists while(true){}.
function tsNever1() :never {
throw new Error('Throw Exception or never return');
}
function *tsNever2() :never {
while(true) {
// ...}}Copy the code
Base type compatibility
Undefined && NULL compatibility
Undefined and null are subtypes that can be assigned to other types. In the tsconfig. Json in:
strictNullChecks
If false, undefined and null can be assigned to divisionnever
Variable of any type outside.strictNullChecks
When true, undefined can only be assigned tovoid
,any
Type variable.
let tsNum: number = undefined; // Error when strictNullChecks is true
let tsVoid: void = undefined; // Ok
Copy the code
Void compatibility
When void is the return value type, it can be replaced by another type.
let foo = function () :void {};let bar = function () :number { return 1; }
foo = bar; // Ok, foo's type is compatible with bar's type
bar = foo; // Error
Copy the code
Void vs. undefined undefined is a subtype of void.
- In JS, void is the operator and always returns undefined; Undefined can be used as a variable in loose mode.
- In the TS,
void
As a return value type, can be replaced by another type, andundefined
I can’t.
Never compatibility
Never is a subtype of all types and can be assigned to any type. In the tsconfig. Json in:
strictNullChecks
When false, it can be assigned directly to any type.strictNullChecks
Is true,never
Can only be used after assignment.
let foo = function () :never { throw 'never' }
/ / number type
let tsNum: number;
/ / never type
let tsNever1 = foo();
let tsNever2: never;
tsNum = tsNever1; // OK, never can be assigned to number
tsNum = tsNever2; // Error when 'strictNullChecks' is true
Copy the code
Any compatibility
TS also adds the any type, which is used when TS checking is not desired.
- Any type can be assigned to
any
Type. any
Types can be assigned to other types (never
Except).
let tsAny: any = 'any value';
let tsNum: number = tsAny; // Ok, any type can be assigned to other types
tsAny = true; // Ok, any type can be assigned to any type
Copy the code
Any type can also be assigned to Object (everything), but it will be type-checked
let foo: any = 1;
let bar: Object = 1;
foo.toFixed(); // OK, no type checking will be done
bar.toFixed(); // Error
Copy the code
Unknow compatibility
TS added unknow is safer than any.
- Any type can be assigned to
unknown
Type. unknown
A type cannot be assigned to another type
let unKnow: unknown;
unKnow = 1; // Ok
unKnow = 'TS'; // Ok
unKnow.length; // Error
let foo: string = unKnow; // Error
Copy the code
Basic wrapper object compatibility
TS supports basic packaging types Boolean, Number, String, and Symbol. The base type is a subtype of the corresponding base wrapper type.
// Basic package type Boolean
let tsBool1: Boolean = new Boolean(a);// The basic type is a subtype of the basic packaging type
let tsBool2: Boolean = false;
Copy the code
3 Reference Types
Reference Type
- Supports Object, Array,
Date
,RegExp
,Error
, Function, Class, etc - new
tuple
,enum
type
Object
{prop: T} describes the structure of object types.
let obj: { a: number } = { a: 1 };
obj.a = 2; // OK
obj.b; // Error
Copy the code
Note: Object describes an object type similar to {}
let obj1: {} = { a: 1 };
let obj2: object = { a: 1 };
obj1.a; // Error: Property 'a' does not exist on type '{}'
obj2.a; // Error: Property 'a' does not exist on type 'object'
Copy the code
Array
There are three definitions (the last two are explained in the next chapter):
- After the type and
[]
, i.e.,T[]
- Array Generic Array Generic :
Array<T>
ReadonlyArray<T>
- Number Index Signature Indicates the Number Index SignatureThrough:
interface
Define the type of
let tsArr1: string[] = ['foo'];
// Array generics
let tsArr2: Array<string> = ['foo'];
let readonlyArr: ReadonlyArray<string> = ['foo']; // Read-only array
// Numeric index signature
interface IdxType { [index: number] :string }
let tsArr3: IdxType = ['foo'];
Copy the code
Tuple
Tuple: An array of known fixed elements and types
let tsTuple: [string.number] = ['foo'.1];
tsTuple[0] = 1; // Error
tsTuple[2]; // Error, an Error will be displayed when accessing elements other than the index
Copy the code
Enum
Enumeration: Defines a set of named constants (enumerators are read-only)
- Numeric enums is a Numeric enumeration: You can define an initial value (default is 0) and then increments according to the initial value.
enum NumericEnum { Foo = 2, Bar, Baz };
/* The compiler reversibly maps to var NumericEnum; (function (NumericEnum) { NumericEnum[NumericEnum["Foo"] = 2] = "Foo"; NumericEnum[NumericEnum["Bar"] = 3] = "Bar"; NumericEnum[NumericEnum["Baz"] = 4] = "Baz"; })(NumericEnum || (NumericEnum = {})); * /
let num: NumericEnum = NumericEnum.Bar; / / 3
let str: string = NumericEnum[3]; // Bar
Copy the code
- String enums Enumeration of characters
enum StringEnum { No = 'NO', Yes = 'YES' }
/* var StringEnum; (function (StringEnum) { StringEnum["No"] = "NO"; StringEnum["Yes"] = "YES"; })(StringEnum || (StringEnum = {})); * /
Copy the code
- Heterogeneous enumeration
enum HeterogeneousEnum { No = 0, Yes = "YES" }
/* var HeterogeneousEnum; (function (HeterogeneousEnum) { HeterogeneousEnum[HeterogeneousEnum["No"] = 0] = "No"; HeterogeneousEnum["Yes"] = "YES"; })(HeterogeneousEnum || (HeterogeneousEnum = {})); * /
Copy the code
Date RegExp Error
let date: Date = new Date(a);let reg: RegExp = /\.ts$/;
let err: Error = new Error('error');
Copy the code
Function
Describes parameter and return value types
(paramter: T): U
Description function definition: (paramter: T) => U
Description function variable
// Define a function declaration
function fn1(s: string) :string {
return s;
}
// Define the arrow function expression
let fn2 = (s: string) :string= > s;
// function variable fn
let fn3: (str: string) = > string = fn2;
Copy the code
parameter
- Required Parameters This parameter is mandatory :
foo: T
- Parameter Description Optional Parameters This parameter is optional :
foo? : T
- Default Parameters Default parameters :
foo: T = value
- Rest parameter Remaining parameters :
. rest: T[]
let fn = (
s: string.// This parameter is mandatory
b: string = ' '.// Default parametersc? :string.// Optional parameters; After the mandatory parameter. d:string[] // Rest parameters; At the end of the parameter) :string= > s;
Copy the code
overloading
// Overload
function reverse(x: number) :number;
function reverse(x: string) :string;
function reverse(x: number | string) :number | string {
if (typeof x === 'number') {
return Number(x.toString().split(' ').reverse().join(' '));
} else if (typeof x === 'string') {
return x.split(' ').reverse().join(' '); }}Copy the code
Class
TypeScript retains ES6 syntax. Here’s how classes are created and inherited using ES6 and TS syntax, respectively:
/ / ES6 syntax
class A {
constructor(msg) {
this.foo = msg;
}
getFoo() {
return this.foo; }}class B extends A {
constructor(msg) {
super(msg);
}
getFoo() {
return 'b' + super.getFoo(); }}Copy the code
/ / TS syntax
class A {
foo: string
constructor(msg: string) {
this.foo = msg;
}
getFoo() {
return this.foo; }}class B extends A {
constructor(msg: string) {
super(msg);
}
getFoo() {
return 'b' + super.getFoo(); }}Copy the code
TS adds functionality to class on top of ES6.
Three types of access modifiers:
public
In TS, members are public by default.private
Private members can only be accessed within the class, not outside the class.protected
Protected members can only be accessed in classes and subclasses.
class A {
public foo: string; // foo: string;
private bar: string;
protected baz: string;
constructor(msg: string) {
this.foo = msg;
this.bar = msg;
this.baz = msg;
}
getFoo() {
return this.foo; }}class B extends A {
constructor(msg: string) {
super(msg);
this.foo; // Ok
this.bar; // Error: Property 'bar' is private and only accessible within class 'A'.
this.baz; // Ok
}
getFoo() {
return super.getFoo() + 'b'; }}const b = new B('str');
b.foo; // Ok
b.bar; // Error: Property 'bar' is private and only accessible within class 'A'.
b.baz; // Error: Property 'baz' is protected and only accessible within class 'A' and its subclasses
Copy the code
Abstract classes: Use abstract to define abstract classes and abstract methods in abstract classes
- Abstract classes are not allowed to be instantiated.
- Abstract methods in abstract classes contain no concrete implementation and must be implemented in derived classes.
abstract class A {
foo: string;
constructor(msg: string) {
this.foo = msg;
}
// Abstract methods do not contain concrete implementations
abstract getFoo(): string;
}
class B extends A {
// Abstract methods must be implemented in derived classes
getFoo() {
return this.foo; }}Copy the code
conclusion
This article covers the native data types of TS, and the next article covers how to customize the types.
agreement
This work is licensed under a Creative Commons Attribution – Non-commercial – No Deduction 4.0 International License.
Exploring TypeScript Type Annotations
- [x] extended JavaScript
- [x] Data type
- [x] User-defined type
- [x] Type check
- [x] Advanced type
- [x] type programming
Refer to the link
Faced: github.com/microsoft/T…