基础
基本命令
- tsc index.ts 把ts转换为js文件
- tsc --init 产生一个ts的config文件
- tsc --watch 每次写完ts不用执行tsc index.ts就会自动帮你生成js文件
- tsc --noEmitOnError --watch 当你ts报错,是不会帮你编译成js的
tsconfig.json
降级编译
为了把ts文件编译成浏览器可以识别的代码,有些浏览器并不支持ES6及以上,所以可以通过配置文件里的target
'target':"es5"//编译出来的js文件是es5语法
严格模式
为了让用户有不同的代码检查规范,比如说undefind不报错,具体看个人喜好,本人比较喜欢把检查类型都打开
"strict": true, //打开严格模式,只要打开这个,下面俩个相当于都打开了
"noImplicitAny": true, //就是必须给值赋类型
"strictNullChecks": true, //不能给其他类型赋值undefind与null
基本类型
interface与type的区别
首先应该知道,我们通过interface定义的类型都可以通过type进行定义
区别
- interface通过extends进行继承,而type通过&进行继承
interface Animal {
name:string
}
interface Bear extends Animal {
honry:boolean
}
const bear:Bear={
name:'winter',
honry:true
}
//type的扩展
//type通过&符号进行继承
type typeAnimal ={
name:string
}
type typeBear=typeAnimal &{
honey:boolean
}
const typebear:typeBear ={
name:'summer',
honey:true
}
2.interface可以进行叠加定义,type不行,会报...重复的error
interface fuilt {
name:string
}
interface fuilt{
num:number
}
const apple:fuilt={
name:'apple',
num:3 //从这里可以看到interface是可以叠加的
}
//type的叠加
type typeFuilt ={
name:string
}
type typeFuilt ={ //type不会叠加,会报错““typeFuilt”重复”
num:number
}
断言 as
是在我们并不清楚变量的类型是什么的时候就可以通过断言的方式来规范 例子
const myCanvns =document.getElementById('main_canvas') as HTMLCanvasElement
const myCanvns1 =<HTMLCanvasElement>document.getElementById('main_canvas')
const x ='hello' as number //这样的断言会报error
//倘若我们不知道hello的类型可以通过下面这种方式
const x1 =("hello" as unknown) as number
文字类型
//1.可以通过let模拟const
let hello:"word"='word',
hello='hello'//会报错,只能是字符串“word”
//2.用处
function getpositon(position:'text-align',aligment:'center'|'right'|'left'):string{
return `${position}:${aligment}`
}
getpositon('text-align','center') //第一个参数只能是'text-align',第二个参数正能是'center'|'right'|'left',若是其他的就会报错
# as const
as const 被称为 const 类型断言,const 类型断言告诉编译器,要将这个表达式推断为最具体的类型,如果不使用它的话,编译器会使用默认的类型推断行为,可能会把表达式推断为更通用的类型
let b = 2 as const
b = 3 // 不能将类型“3”分配给类型“2”。
//`b`变量就转为常量,`b`的类型为`2`,不能改变
let a=[1,'2'] as const
function mynum1 (num:number){
console.log(num);
}
mynum1(a[0]) //前面不加as const 会报error,'类型“string | number”的参数不能赋给类型“number”的参数'
?与!
?
?可以把变量定义为可以是未定义类型,也就是undefind
// 由于x是可选的,因此parma.x的类型为number | undefined,无法传递给number类型的y,因此需要用x!
interface IDemo {
x?: number
}
let y:number
const demo = (parma: IDemo) => {
y = parma.x! //或者使用 y = parma.x|| 1
return y
}