React

TypeScript 5分钟入门

2018-12-07  本文已影响0人  南方帅

参考官方文档

1 安装 & 编译

- yarn global add typescript
- tsc demo.ts

2 增强

静态类型

function greeter(person: string) {
}
// 约定传参为string类型 出错会提示但是允许允许

interface

interface Person {
  firstName: string;
  lastName: string;
}
function greeter(person: Person){
}
// 约定传参接口
// 使用 ?: 表示可以忽略这个值
interface style {
  height ?: number;
  width ?: number;
}
interface中没有定义的话 传入会报错

基础类型

let isDone: boolean = false;
let decimal: number = 6;
let color: string = 'blue'
let list:number[] = [1,2,3]
let list:Array<number> = [1,2,3] // 后面参数必填
let tuple: [string, number]   // ["hello", 10]

enum Color {Red, Green, Blue}
let c:Color = Color.Green  //1  enum 必须有对应的值 或者默认数字

为了兼容现有的 这个类型约定相当于没有
let notSure: any= 4  => 同js let notSure = 4;  不会报错
其他  null undefined void
Object 除了以上其他
declare function create(o: object | null): void;

create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error

readonly ReadonlyArray

readonly 用于属性, const 用于变量

interface circle {
  readonly R : number;
}
let ro: ReadonlyArray<number> = [1,2,3,4];

函数返回值

限定函数返回值类型

interface SquareConfig {
  width: number;
  height ?:number;
}
function calcArea(square: SquareConfig) : {width: number, area:number} {
  if(square.height) {
    return {width: square.width, area: square.width * square.width}
  } else {
    return {width:square.width, area:square.width * square.height}
  }
}
let square1 = calcArea({width: 100, height: 500});

同样也可以直接用interface

interface isExisted {
  (source: string, subString: string): boolean
}
let mySearch: isExisted;
mySearch = function (source: string, subString: string): boolean {
  let result = source.search(subString);
  return result > -1;
}
上一篇下一篇

猜你喜欢

热点阅读