ts学习1 typescript

// 微软开发ts

// ts可以使用es7 es6 es5

// cnpm i typescript -g 会得到一个全局命令tsc

let zname:string = 'hello';

//zname是变量 变量的类型 是字符串

//编译 tsc 1.ts 编译后变成1.js文件

// 两个文件 变量名 一样 也会冲突

export default {name:'guozimo'}// ts看到这样的东西 会认为他是一个模块 所以不报变量重复的错误

// package.json 构建脚本

"scripts":{

"build": "tsc",

"dev": "tsc --watch"// 监控文件的变化

}

// 生成一个配置文件ts

tsc --init // 命令行生成配置文件 生成tsconfig.json

// 在导出对象上增加一个default属性

// commonjs的写法

import * as React from 'react'

// ts需要这样引用react 不报错



 

tsconfig.json文件中

以commonjs形式编译 挂在module的defined属性上

"esModuleInterop":true// 如果使用react报错了 那么就用这个true

"esModuleInterop":false

// npm run build 就生成了ts文件了

npm run dev 监控变化 自动变化

// vscode作者和ts作者是一个人

let zname:string = 'hello';

let age:number = 10;

let married:boolean = true

// 数组的第一种写法

let hobbies:number[]=[1,2,3]// number 的数组

let hobbies1:string[]=['1','2','3']// 字符串的数组

// 数组的第二种写法

let arr2:Array<number>=[4,5,6]

// 元组 java c中都有 特殊数组 表示一个数量和类型都已知的数组 顺序也是固定的

let guozimo:[string,number]=['guozimo',10]// 元组的每一项可以是不一样的 数组是每一项都必须一样

let point:[number,number]=[100,100];// 坐标

// 元组有固定长度 数组长度没有限制

枚举类型(enum)

// 性别 月份 星期 颜色 单位 学历

enum Gender{

BOY,

GIRL

}

let g1:Gender= Gender.BOY;

let g2:Gender=Gender.GIRL;

//编译后就是一个自执行函数

// 常数枚举

const enum Color{

RED,

YELLOW,

BLUE

}// 编译完后就被删除了

console.log(Color)// 报错

console.log(Color.RED)// 只能这样用

// 任何类型

export {}

let root:(HTMLElement|null) =document.getElementById('root')

root!.style.color='red';

// ! 强行忽略警示

let root1:any =document.getElementById('root')

root!.style.color='red';

let x:number;

// undefined 是number的子类型 修改ts的配置文件strictNullChecks:false // 可以赋值null 或者unndefined

x=10

x=undefined // 配置文件修改后就能设置了

x=null

// 也可以写成下面的形式 不用修改配置文件

let x1:number | null|undefined;

// void 表示没有任何类型

function greeting(name:string):void{

// void 函数没有反回值 写返回值则会报错

return undefined; // 等同写了void

}

// never 类型 永远不出现的值

function sum():never{

while(true){

// 函数永远不会返回 那么返回值类型就是never

}

}

// 返回前抛出错误 那么他也永远不会正常结束

function minus():never{

throw Error('我错了');

}

function double(x:number|string){

if(typeof x=='number'){

console.log(x);

}else if(typeof x=='string'){

}else {

console.log(x);

// never类型

}

}

// ts-ignore 忽略ts检查














 

发布了363 篇原创文章 · 获赞 32 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/gwdgwd123/article/details/104309980