当前位置:网站首页>Typescript: Basics
Typescript: Basics
2022-04-22 05:51:00 【Ha! Xiaobai wants to grow!】
List of articles
Strong type and weak type
notes : There is no clear definition in the industry
Strong type language : Arbitrary implicit type conversions are not allowed
Weak type language : Allow any implicit data type conversion ( Shape parameter 、 The data types of arguments are allowed to be inconsistent )
// Weak type
function sum(a, b) {
if(typeof(a) !== number || typeof(b) !== number) {
throw new TypeError(' Wrong parameter type ')
}
return a + b
}
// Strong type : Parameter type judgment is not required , Because parameters with inconsistent types will not be passed
function sum(a, b) {
return a + b
}
Strong type language :
- Mistakes are exposed earlier
- Code is smarter , More accurate coding
- Refactoring is more robust
- Reduce unnecessary type judgments
Flow
// Type notes
function sum(a: number, b: number) {
return a + b
}
// call
sum(5, 2) // correct
sum('5', 2) // Report errors
typescript
1、 Raw data type
const a: string = 'string'
const b: number = 100 // You can also store :NaN perhaps Infinity( infinite )
const c: boolean = true
// string、number、boolean The value of type variable can be null , It can be for null、undefined
const d: void = undefined // Empty type , The value is null、undefined, It is generally used to mark the return type of a function without a return
const e: null = null
const f: undefined = undefined
const h: symbol = Symbol()
2、 Scope
Separate scopes :
- Immediate execution function
- modular
// Use execute now function
(function() {
const a = 100
})()
// Use export ( modular )
const a = 100
export {
}
3、object type
The value can be : Array 、 object 、 function ( Types other than the original type ), It cannot be a normal object type
const foo: object = []
const foo: object = {
}
const foo: object = function() {
}
Definition of common object types :
// Object type restrictions ( A more professional way is to use interfaces )
const obj: {
a: number, b: string} = {
a: 100, b: 'string'}
4、 Array
// The definition of an array composed of pure numbers
const arr1: Array<number> = [1, 2, 3]
const arr2: number[] = [1, 2 3]
5、 A tuple type
const tuple: [number, string] = [20, 'zc']
// Get tuple members : Subscript mode
const age = tuple[0]
const name = tuple[1]
// Get tuple members : Array deconstruction method
const [age, name] = tuple
6、 Enumeration type
JavaScript There are no enumeration types in the , Use object simulation to realize
const enumData = {
key: value // key: Enumeration member names
}
// value It could be a string , However, self growth cannot be carried out at this time , You need to assign values to each member manually
7、 Function type
Restrictions on function declarations
export {
} // Make sure there are no member conflicts with other examples
// Functions with type constraints ( Via type annotation ): When calling, the number of parameters should be consistent
function fun1(a: number, b: number): string {
// number: Parameter type ;string: Function return value type
return ' Return value '
}
// Add optional parameters
// The way 1: add to ?
function fun2(a: number, b?: number): string {
}
// The way 2: Add default
function fun2(a: number, b: number = 10): string {
}
// Receive any number of parameters :rest The operator
function fun2(a: number, b: number, ...rest: number[]): string {
}
Restrictions on function expressions
export {
} // Make sure there are no member conflicts with other examples
const fun: (a: number, b: number) => string = function(a: number, b: number): string{
return ' Return value '
}
8、 Any type
export {
} // Make sure there are no member conflicts with other examples
let a: any = 100
any = 'string'
9、 Implicit type inference
Variables are defined without specifying data types or assigning values , Then the variable type is any, After that, random assignment will not cause syntax errors
export {
} // Make sure there are no member conflicts with other examples
let a
a = 10
a = 'string'
However, it is recommended to add explicit data types for each variable
10、 Types of assertions
Assertion : tell typescript A variable is of a data type
export {
} // Make sure there are no member conflicts with other examples
// The way 1
const n = r as number // r yes number type
// The way 2
const n = <number>r // stay JSX Next not available ( Will conflict with the label )
11、 Interface
Interface : Used to constrain the structure of an object ( Make type constraints on structured data )
- Optional members
- Read only members
- Dynamic members
export {
} // Make sure there are no member conflicts with other examples
interface Post{
title: string; // member : type
content: string;
subTitle?: string; // Optional members
readonly summary: string; // Read only members
}
function printPost(post: Post) {
// post Type is limited to Post Interface type
console.log(post.title);
console.log(post.content);
}
printPost({
title: 'Hello TypeScript', // Parameters
content: 'A javascript superset',
summary: 'superset' // Read only members , It is not allowed to be modified after initialization
})
Dynamic members :
export {
}
interface Cache{
[prop: string]: string
}
const cache: Cache = {
}
cache.a = 'a' // Add members dynamically
cache.b = 'b'
12、 class
class : An abstract member that describes a class of concrete objects
ES6 Before : function + Prototype , Simulation implementation class
ES6: With class
12.1 Attributes of a class 、 Constructors 、 function
export {
}
class Person{
// Class properties / member
name: string = 'init name' // Initial value
age: number
// Constructors constructor
constructor(name: string, age: number) {
this.name = name
}
// function
sayHi(msg: string): void {
console.log(`I am ${
this.name},${
msg}`)
}
}
12.2 Class access modifier
public: share
private: private
protected: Allow access to... In subclasses
12.3 Modifier for constructor
- public
- private: This class is not allowed to be instantiated 、 Not allowed to be inherited , Can only be instantiated internally
export {
}
class Person{
name: string = 'init name'
age: number
gender: string
constructor(name: string, age: number) {
this.name = name
this.age = age
this.gender = gender
}
sayHi(msg: string): void {
console.log(`I am ${
this.name},${
msg}`)
}
}
class Student extends Person{
// Constructor settings private Modifier , be Student Class is not allowed to be used outside of it new establish ( Cannot be instantiated ), It is not allowed to be inherited
private constructor(name: string, age: number){
super(name, age)
console.log(this.gender)
}
static create(name: string, age: number){
return new Student(name. age) // Internally, it is allowed to be new( Allow to be instantiated )
}
}
const jack = Student('jack', 18)
12.4 Class's read-only properties
readonly Decorated attributes
readonly When using , Put it after the modifier
The initialization of read-only attributes is performed at the time of declaration or in the constructor
12.5 Classes and interfaces
Different classes implement the same interface
Class implementation interface
export{
}
interface EatAndRun{
eat(food: string): void // member
run(distance: number): void
}
class Person implements EatAndRun{
// Implementation interface EatAndRun( Be careful : To implement the interface, all members must be included )
eat(food: strign): void{
console.log(` Eat with grace :${
food}`)
}
run(distance: number): void{
console.log(` Walk upright :${
distance}`)
}
}
class Animal implements EatAndRun{
eat(food: strign): void{
console.log(` Snore and eat :${
food}`)
}
run(distance: number): void{
console.log(` crawl :${
distance}`)
}
}
A class implements multiple interfaces at the same time
export{
}
interface Eat{
eat(food: string): void // member
}
interface Run{
run(distance: number): void
}
class Person implements Eat, Run{
// Implementation interface EatAndRun( Be careful : To implement the interface, all members must be included )
eat(food: strign): void{
console.log(` Eat with grace :${
food}`)
}
run(distance: number): void{
console.log(` Walk upright :${
distance}`)
}
}
class Animal implements Eat, Run{
eat(food: strign): void{
console.log(` Snore and eat :${
food}`)
}
run(distance: number): void{
console.log(` crawl :${
distance}`)
}
}
12.6 abstract class
abstract class : Can include specific implementations
Interface : It can only be the abstraction of members , No concrete implementation
Abstract classes can only be inherited , Can't be instantiated
Methods don't need Abstract bodies ; Abstract methods are implemented in subclasses
export {
}
// abstract class
abstract class Animal{
eat(food: string): void{
console.log(` Snoring and eating :${
food}`)
}
// Abstract method
abstract run(distance: number): void
}
class Dog extends Animal{
run(distance: number): void{
console.log(` Crawling on all fours `, distance)
}
}
const d = new Dog()
d.eat(' Dog food ')
d.run(100)
13、 Generic
Defining functions in 、 Interface 、 Class without specifying the data type , When used, specify
Use generics , It's good for code reuse
13.1 Redundant creation
export {
}
// establish number Type array
function createNumberArray(length: number, value: number): number[]{
const arr = Array<number>(length).fill(value) // adopt <number> Specifies that the type of array to be created is number Type array
// Array(length): Create a length of length Array of , The default is any type
// fill() Method is used to populate the data
return arr
}
const res = createNumberArray(3, 100)
// result :res → [100, 100, 100]
// establish string Type array
function createStringArray(length: number, value: string): string[]{
const arr = Array<string>(length).fill(value)
return arr
}
13.2 Create without redundancy : Use generics
export{
}
// T: Generic parameter name
function createArray<T>(length: number, value: T): T[]{
const arr = Array<T>(length).fill(value)
return arr
}
// string: The generic parameter
const res = createArray<number>(3, 100)
版权声明
本文为[Ha! Xiaobai wants to grow!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220536391831.html
边栏推荐
猜你喜欢

Data processing code record

raspberry keras-ocr can‘t allocate memory in static TLS block

09-Redis之IO多路复用

TCGA数据库ensembl id 转为 gene Symbol,提取出需要的RNA种类表达谱列表信息

Circular linked list 2

vs 断点无法调试 The breakpoint will not currently be hit. No symbols have been loaded for this document.

通过设置关联菜单建立excel记账本

卷积神经网络

Complete knapsack problem

Force buckle 237 Delete specified node list
随机推荐
Discounted split plane
数据挖掘——数据预处理
TCGA数据库ensembl id 转为 gene Symbol,提取出需要的RNA种类表达谱列表信息
Pseudo code block writing (for paper writing)
torch nn.Parameter可训练参数定义
卷积神经网络
List stream: usage instance of reduce
蓝桥杯冲刺——DFS
不用第三个变量交换两变量值的几种方式
《PyTorch深度学习实践》Lecture_10 卷积神经网络基础 CNN
记录一次项目经历和项目中遇到的技术
为什么要引入协程
等腰三角形-第九届蓝桥省赛-C组
09-Redis之IO多路复用
牛客练习赛97
List分割最佳实践
《PyTorch深度学习实践》Lecture_11 卷积神经网络进阶 Convolutional Neural Network
uniapp:HBuilderX运行uniapp项目到夜神模拟器
元注解(注解的注解)
Fastjson determines whether the JSON string is object or list < object >