入门

作者: zdxhxh | 来源:发表于2020-02-19 10:00 被阅读0次

编译ts文件

cnpm i typescript -g 
tsc -v
tsc hello.ts
node hello.js

类型注解

typescript 可以给函数参数添加类型注解,如下

function hello(world : string) { 
  console.log(world)
}

类型注解是一种轻量级的为函数或变量添加约束的方式。

接口

在typescript中,只要两个类型内部结构兼容,那么这两个类型就是兼容的,这允许我们使用接口保证接口要求的结构就可以了,而不必要使用implements

interface Person { 
  firstname : string
  lastName : string 
}

function hello(person : Person) {
  console.log(`hellor : ${person.firstname}`)
}

Typescript支持Javascript的新特性,比如基于面向对象编程。

class User { 
  fullName : string
  firstName : string
  lastName : string 
  
  constructor(firstName : string,lastName : string) { 
    this.firstName = firstName
    this.lastName = lastName
    this.fullName = firstName + ' ' + lastName
  }
}

interface Person { 
  firstname : string
  lastName : string 
}
function hello(person : Person) {
  console.log(`hellor : ${person.firstname}`)
}
hello(new User('yang','yan'))

类型断言

你自信的认为你会比Typescript更了解某个值的详细信息,通常这会发生在你清楚的知道一个实体具有比它现有类型更确切的类型。

类型断言好比其他语言的类型强转,但是不进行特殊的数据检查。它在运行时没有影响,只在编译阶段起作用。Typescript会假设该程序员已经进行了必要的检查了。

它有两种形式。

let someValue : any = "this is a string "
let strLength: number = (<string>someValue).length

另一个是as的写法

let someValue: any = 'this is a string'

let strLength: number = (someValue as string).length

注意 : 在jsx中,只有as语法断言是被允许的。

相关文章

网友评论

      本文标题:入门

      本文链接:https://www.haomeiwen.com/subject/suiofhtx.html