<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
mounted() {
this.baseType(); //11 Basic type definitions
this.interfaceDemo(); //interface Interface
this.classType(); // class
this.genericType(); // Generic
this.interfaceOrType(); // Interface (interface) And type aliases type
this.getDeclare(); //Declare Declaration file
},
methods: {
/**
* Declare keyword
* */
getDeclare() {
// We are .ts Third party libraries used in do not .d.ts When declaring a document , We can go through declare To write a statement .
// The module can be declared , You can even directly declare a value as any A variable with the same name as , Then we can use the third-party library directly in our code .
},
/**
* Introduce the interface (interface) And type aliases type The differences and use scenarios
* @description Generally speaking , It works interface Realization , Just use interface, If not, use it type
*/
interfaceOrType() {
// One thing in common : Can describe an object or function ,type and interface The grammar of is different ,type An equal sign is required , and interface You don't need an equal sign
interface User {
// Describe an object
name: string;
age: number;
}
interface SetUser {
// Describe a function
(name: string, age: number): void;
}
type UserType = {
// Describe an object
name: string;
age: number;
};
type SetUserType = {
// Describe a function
(name: string, age: number): void;
};
let test: SetUserType;
test = function (name: string, age: number): void {
console.log(111);
};
// Same point two : Are allowed to expand (extends) inheritance of attribute
//1.interface inheritance of attribute
interface dudu1 {
name: string;
}
interface dudu2 extends dudu1 {
age: number;
}
const duduTest: dudu2 = { name: "zyb", age: 23 };
//2.type Type inheritance type type
type Nametype = {
name: string;
};
type UserType1 = Nametype & { age: number };
const valueType: UserType1 = { name: "zyb", age: 23 };
//3.interface extends type ( Interface inheritance type )
type LulvwaType = {
name: string;
};
interface LulvwaFace extends LulvwaType {
age: number;
}
const LulvwaValue: LulvwaFace = { name: "zyb", age: 23 };
//4.type extends interface ( Type inheritance interface )
interface shajFace {
name: string;
}
type shajType = shajFace & {
age: number;
};
const shajValue: shajType = { name: "zyb", age: 23 };
// One difference :type You can declare basic type aliases , Joint type , Tuples and so on , and interface no way
//1、 Basic type alias
type DiffName = string;
// 2. Joint type
interface Dog {
wong(): void;
}
interface Cat {
miao(): void;
}
type Pet = Dog | Cat;
// Define the type of each position of the array
type PetList = [Dog, Pet];
//2.type You can also use typeof Get the type of the instance to assign
let div = document.createElement("div");
type B = typeof div;
//3.type Other operations
type StringOrNumber = string | number;
type Text = string | { text: string };
type Callback<T> = (data: T) => void;
type Pair<T> = [T, T];
type Coordinates = Pair<number>;
type Tree<T> = T | { left: Tree<T>; right: Tree<T> };
//4.interface Be able to declare a merger
interface User {
name: string;
age: number;
}
interface User {
sex: string;
}
},
/**
* Generic
* @des A generic type refers to a type , More like a type variable . Wrapped in angle brackets <T>
* @des The main function is to create logically reusable components
* @des Generics can act on functions 、 class 、 On the interface
*/
genericType() {
//*************** Defined function *****************/
function greet<T>(arg: T): T {
return arg;
}
//*************** Defining classes *****************/
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
constructor(zeroValue: T, add: (x: T, y: T) => T) {
this.zeroValue = zeroValue;
this.add = add;
}
}
let myGenericNumber = new GenericNumber<number>(1, (a, b) => a + b);
myGenericNumber.zeroValue = 0;
const result = myGenericNumber.add(40, 2);
//*************** Defining interfaces *****************/
// The first definition : Generic interface
interface ConfigFns {
<T>(value1: T): T; // Generic interface
}
var getData: ConfigFns = function <T>(value1: T): T {
return value1;
};
getData<string>("OK");
// The second way to define it
interface ConfigFnplus<T> {
(value1: T): T; // Generic interface
}
function getData1<T>(value1: T): T {
return value1;
}
var myGetData: ConfigFnplus<string> = getData1;
myGetData("OK,wo");
//*************** Generic constraint ( Generics can also be constrained , This is not to accept any type , It must be accepted that length Object of property )*****************/
interface TIF {
length: number;
}
function test<T extends TIF>(params: T) {
console.log("=========>>>", params.length);
}
console.log(test("abc"));
//*************** Define type parameters for generic constraints *****************/
function getPropoty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let obj = { a: 1, b: "2", c: 3 };
console.log(getPropoty(obj, "c"), "--- Parameters ");
},
/**
* 11 Basic type definitions
* @des number、string、boolean、Array、Tuple( Tuples )、enum( enumeration )、object、never、void、null and undefined、any
*/
baseType() {
//***************①number Except for the first one, they are all base numbers *****************/
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
//***************string*****************/
let name: string = "bob";
// String template
let age: number = 37;
let name1: string = `Gene`;
let sentence: string = `Hello, my name is ${name1}.I'll be ${
age + 1
} years old next month.`;
//***************boolean*****************/
let isDone: boolean = false;
//***************Array*****************/
let list: number[] = [1, 2, 3];
let list1: Array<number> = [1, 2, 3]; // Generic
//***************Tuple( Tuples )*****************/
let x: [string, number];
x = ["hello", 10];
//***************enum( enumeration )*****************/
enum Color {
Red,
Green,
Blue,
} // The default is 0,1,2
let c: Color = Color.Green;
// Manual assignment
enum Color1 {
Red = 1,
Green = 2,
Blue = 4,
}
let c1: Color1 = Color1.Green;
// Manual assignment From what time
enum Color2 {
Red = 1,
Green,
Blue,
} //1,2,3
// Numeric enumerations can be mixed into Calculated and constant members
function getSomeValue() {
return 1;
}
enum E {
A = getSomeValue(),
//B, // error! 'A' is not constant-initialized, so 'B' needs an initializer
}
// String Enum
enum DirectionString {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
// Heterogeneous enumeration ( You can mix string and numeric members , But it seems that you won't do that )
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",
}
//***************object*****************/
let obj: Object;
//***************never(never Types represent types of values that never exist )*****************/
// return never The function of must have an unreachable end point
function error(message: string): never {
throw new Error(message);
}
//***************void( When the function does not return a value )*****************/
function warnUser(): void {
console.log("This is my warning message");
}
//***************null and undefined*****************/
let u: undefined = undefined;
let n: null = null;
//***************any*****************/
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
},
/**
* interface Interface in several ways
* @des Define the object 、 Define an array 、 Defined function 、 Defining classes 、 Interfaces inherit from each other 、 Optional properties and additional checks
*/
interfaceDemo() {
// Interface interface Related definitions ---start====
//***************① Define the object *****************/
interface Cat {
color: string;
}
let yellowCat: Cat = {
color: "yellow",
};
//***************① Define an array *****************/
interface List {
[index: number]: string;
}
let list: List = ["one", "two"];
//***************① Defined function *****************/
// Common interface
interface discount1{
getNum : (price:number) => number
}
function testFun(discount1: discount1):void{
console.log(discount1.getNum);
}
// Function type interface
interface discount2{
// Be careful :
// “:” Before that is the signature of the function , The parameters used to constrain the function
// ":" The following is used to constrain the return value of the function
(price:number):number
}
let cost:discount2 = function(price:number):number{
return price * .8;
}
interface Fun {
(name: string): void;
}
let fun: Fun = function (a: string) {
console.log(a);
};
//***************① Defining classes *****************/
interface Person {
name: string;
age: number;
}
class People implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
//***************① Interfaces inherit from each other *****************/
interface Shape {
color: string;
}
interface Sqaure extends Shape {
sideLength: number;
}
let square: Sqaure = {
color: "red",
sideLength: 11,
};
//***************① Optional properties and additional checks *****************/
interface TestConfig {
color?: string;
width?: number;
[propsName: string]: any;
}
function createTest(config: TestConfig): any {}
let myTest = createTest({ color: "red", width: 20 });
// *********** Indexable type interface ***********/
// Digital index —— Constraint array
// index It's a random name , You can call it anything
// as long as index The type is number, Then the type of value must be string
interface StringArray {
// key The type of number , It's usually an array
// Limit value The type of string
[index: number]: string;
}
let arr: StringArray = ["aaa", "bbb"];
console.log(arr);
// String index —— Constrain objects
// as long as index The type is string, Then the type of value must be string
interface StringObject {
// key The type of string , Generally speaking, it represents an object
// Limit value The type of string
[index: string]: string;
}
let obj: StringObject = { name: "ccc" };
// function overloading
function attr(val: any): any {
if (typeof val === 'string') {
return val;
} else if (typeof val === 'number') {
return val;
}
}
alert(attr('aaa'));
attr(666);
// Interface interface Related definitions ---end====
},
/**
* Class
* @des Members of the public (public)、 Private member (private)、 Protected members (protected)、 Static attribute (static)
* @des Inherit extends
* @des abstract class abstract
*/
classType() {
class tsClass {
public a: string; // Members of the public
private b: number[]; // Private member
protected c: string[]; // Protected members
static e: string = "e"; // Static attribute
constructor(astr: string, barr: number[], carr: string[]) {
this.a = astr;
this.b = barr;
this.c = carr;
}
}
class SublevelCla extends tsClass {
private dname: string; // Private member
constructor(
astr: string,
barr: number[],
carr: string[],
dname: string
) {
super(astr, barr, carr); // Inherit tsClass Field construction
this.dname = dname; //sublevelCla Self constructed field
}
fun(): void {
console.log(tsClass.e); // Get static members through classes
}
}
let sub = new SublevelCla(
"a",
[1, 2, 3],
["a", "b", "c"],
"sublevelName"
);
sub.fun();
console.log(sub.a);
// console.log(sub.b); // Report errors : Private members cannot be accessed externally
// console.log(sub.c); // Report errors : Protected members cannot be accessed externally
// console.log(sub.dname); // Report errors : Private members cannot be accessed externally
// -----= abstract class =-----( Abstract classes are used as base classes for other derived classes . They are generally not instantiated directly . Unlike interfaces , Abstract classes can contain implementation details of members . abstract Keywords are used to define abstract classes and abstract methods within abstract classes .)
abstract class Department {
constructor(public name: string) {}
printName(): void {
console.log("Department name: " + this.name);
}
abstract printMeeting(): void; // Must be implemented in a derived class
}
class AccountingDepartment extends Department {
constructor() {
super("Accounting and Auditing"); // Must be called in the constructor of a derived class super()
}
printMeeting(): void {
console.log(
"The Accounting Department meets each Monday at 10am."
);
}
generateReports(): void {
console.log("Generating accounting reports...");
}
}
let department: Department; // Allows you to create a reference to an abstract type
// department = new Department(); // error : Cannot create an instance of an abstract class
department = new AccountingDepartment(); // Allows instantiation and assignment of an abstract subclass
department.printName();
department.printMeeting();
// department.generateReports(); // error : Method does not exist in the declared abstract class
},
},
});
</script>当前位置:网站首页>Typescript learning materials
Typescript learning materials
2022-06-27 15:09:00 【suipa】
边栏推荐
- Brief reading of dynamic networks and conditional computing papers and code collection
- AQS抽象队列同步器
- [OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
- Pisa-Proxy 之 SQL 解析实践
- my. INI file configuration
- The global chip market may stagnate, and China's chip expansion accelerates to improve its self-sufficiency rate against the trend
- ThreadLocal之强、弱、軟、虛引用
- Leetcode 724. Find the central subscript of the array (yes, once)
- Redis master-slave replication, sentinel mode, cluster cluster
- [advanced MySQL] MTS master-slave synchronization principle and Practice Guide (7)
猜你喜欢

基于WEB平台的阅读APP设计与实现

Volatile and JMM

Use GCC to generate an abstract syntax tree "ast" and dump it to Dot file and visualization
![[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)](/img/29/73c381f14a09ecaf36a98d67d76720.png)
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
![[digital signal processing] discrete time signal (discrete time signal knowledge points | signal definition | signal classification | classification according to certainty | classification according t](/img/69/daff175c3c6a8971d631f9e681b114.jpg)
[digital signal processing] discrete time signal (discrete time signal knowledge points | signal definition | signal classification | classification according to certainty | classification according t

QT 如何在背景图中将部分区域设置为透明

Top ten Devops best practices worthy of attention in 2022
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk
![[high concurrency] deeply analyze the callable interface](/img/24/33c3011752c8f04937ad68d85d4ece.jpg)
[high concurrency] deeply analyze the callable interface

Massive data! Second level analysis! Flink+doris build a real-time data warehouse scheme
随机推荐
Brief reading of dynamic networks and conditional computing papers and code collection
Nvidia Deepstream 运行延迟,卡顿,死机处理办法
Talk about redis transactions
2022-2-15 learning the imitated Niuke project - Section 5 shows comments
SQL parsing practice of Pisa proxy
AI begets the moon, and thousands of miles share the literary heart
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
Resolve activity startup - lifecycle Perspective
Programming skills: script scheduling
Design and implementation of reading app based on Web Platform
CAS comparison and exchange
基于 Nebula Graph 构建百亿关系知识图谱实践
Redis persistence
ThreadLocal之强、弱、軟、虛引用
反射学习总结
How to change a matrix into a triple in R language (i.e. three columns: row, col, value)
老师能给我说一下固收+产品主要投资于哪些方面?
How to select cross-border e-commerce multi merchant system
Knightctf 2022 web section
Redis master-slave replication, sentinel mode, cluster cluster