TypeScript基础

TypeScript playgroud

https://www.typescriptlang.org/play

手动建立TypeScript编译

npm install -g typescript

tsc -v

tsc xxx.ts

node xxx.js

工程化自动编译


npm create vite@latest ts-pro -- --template vanilla-ts

-- --template vanilla-ts 创建项目使用的模版为原生ts模版

npm install 
npm run dev

TypeScript基础-数据类型

//基础数据类型
// 布尔
let isDone: boolean = false;
// 数字
let decLiteral: number = 2024;
// 字符串
let str:string = "some word";
// 数组
let list1:number[] = [1,2,3,4];
let list2: Array<string>= ['a','b','c'];
// 元组
let x:[string,number]
x = ['a',1]
// x = [1,'a'] error
// 枚举
enum Color {Red,Green,Blue}
let y = Color.Red
// unknown
let unSure: unknown = 2024
unSure = "some words"
unSure = false
// void,无函数返回值
function test():void{
    console.log("test viod return")
}
//null 和 undefined
let u:undefined = undefined
let n:null = null
//联合类型
let unionTest1:(string|number)[]=[123,'ab','c',456]
let unionTest2:number|string|boolean=123
unionTest2=false
unionTest2="test over"
// 类型别名
type ItemTypeTest = number|string|boolean
let z:ItemTypeTest = 123
// 函数注解
function add1(num1:number,num2:number):number{
    return num1+num2
}

const add2=(num3:number,num4:number):number=>{
    return num3+num4
}
// 可选
function splice(a:string,b?:string){
	if (b){
	return a + b 
	}
	return a
}
// 接口
interface User1 {
	name: string
	age?: number
}
let users: User1[] = [
	{
		name: 'test1',
		age: 33
	},
	{
		name: 'test2',
		age: 33
	}
]
users.forEach(item=>console.log(item.name))
// 接口继承
interface Teacher extends User1{
    sex?:string
}
// type注解对象类型
type User2 = {
	name: string
	age: number
}
// 实现继承
type Person = User2 & {
	sex: number
}
// 字面量类型
type Sex = 'male'|'female'
let sex: Sex = 'male'

TypeScript基础-if及switch

// if语句
let num:number=5
if (num>0){
    console.log('num是正数')
}
//if else语句
if (num%2==0){
    console.log('偶数')
}
else{
    console.log('奇数')
}
//if else if else语句
if (num>0){
    console.log('正数')
}
else if (num < 0){
    console.log('负数')
}
else{
    console.log('零')
}
// switch case
let grade:string='A'
switch(grade){
    case 'A':{
        console.log('优')
        break
    }
    case 'B':{
        console.log('良')
        break
    }
    default:{
        console.log('error')
        break
    }
}

TypeScript基础-函数定义

// 函数定义
function add1(x:number, y:number):number{
    return x + y
}

const add2 = (x:number,y:number):number=>{
    return x+y
}
// 可选参数
function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + ' ' + lastName;
    else
        return firstName;
}

let result1 = buildName('Bob');
let result2 = buildName('Bob', 'Adams'); 

//剩余参数
function getEmployeeName(firstName: string, ...restOfName: string[]) {
  return firstName + ' ' + restOfName.join(' ');
}

let employeeName = getEmployeeName('Joseph', 'Samuel', 'Lucas', 'MacKinzie');

//箭头函数
let testArrowFun = (num: number) => {
  if (num > 0) {
    console.log(num + ' 是正数');
  } else if (num < 0) {
    console.log(num + ' 是负数');
  } else {
    console.log(num + ' 为0');
  }
}
testArrowFun(-1)   //输出日志:-1 是负数

TypeScript基础-类

//类的定义
class Person{
    private name:string
    private age:number

    constructor(name:string,age:number){
        this.name=name
        this.age=age
    }

    public getPersonInfo():string{
        // return 'My name is'+ this.name+ 'and my ages is ' + String(this.age)
        return `My name is ${this.name} and age is ${this.age}`
    }
}

let person1= new Person('Jack',18)
let personinfo = person1.getPersonInfo()
console.log(personinfo)
// 继承
class Employee extends Person {
  private department: string

  constructor(name: string, age: number, department: string) {
    super(name, age);
    this.department = department;
  }

  public getEmployeeInfo(): string {
    return this.getPersonInfo() + ` and work in ${this.department}`;
  }
}
let person2 = new Employee('Black', 28, 'IT');
person2.getPersonInfo();
person2.getEmployeeInfo();

TypeScript基础-模块

// 定义
export class NewsData {
  title: string;
  content: string;
  imagesUrl: Array<string>;
  source: string;

  constructor(title: string, content: string, imagesUrl: Array<string>, source: string) {
    this.title = title;
    this.content = content;
    this.imagesUrl = imagesUrl;
    this.source = source;
  }
}
// 使用
// 模块的导入操作与导出一样简单。 可以使用以下 import形式之一来导入其它模块中的导出内容。
import { NewsData } from '../common/bean/NewsData';

TypeScript基础-迭代

// 迭代
// for..of
let someArray = [1, "string", false];

for (let entry of someArray) {
    console.log(entry); // 1, "string", false
}
// for..of和for..in均可迭代一个列表,但是用于迭代的值却不同:for..in迭代的是对象的键,而for..of则迭代的是对象的值。
let list = [4, 5, 6];

for (let i in list) {
    console.log(i); // "0", "1", "2",
}

for (let i of list) {
    console.log(i); // "4", "5", "6"
}