ts

作者: 萘小蒽 | 来源:发表于2023-10-05 17:10 被阅读0次

基础类型

let isShow:boolean = false; //布尔值 
let str:string = '字符串'; //字符串
let num:number = 1; //数字

函数

函数申明
viod代表该方法没有返回值,等同于返回 undefined
 function hello (txt:string):viod {
      console.log('hello ' + txt);
 }
function f():void {
  return undefined; // 正确
}

function f():void {
  return null; // 报错
}




变量赋值为一个函数

// 写法一
const hello = function (txt:string) {
  console.log('hello ' + txt);
}

// 写法二
const hello: (txt:string) => void
= function (txt) {
  console.log('hello ' + txt);
};
//箭头函数
const repeat = (
  str:string,
  times:number
):string => str.repeat(times);
//函数作为参数传入函数
function greet(
  fn:(a:string) => void
):void {
  fn('world');
}

// 可选参数
function f(x?:number) {
  // ...
}

f(); // OK
f(10); // OK

//never 类型 表示函数肯定不会返回值
function fail(msg:string):never {
  throw new Error(msg);
}

对象 (ts不区分对象自身的属性和继承的属性)

// 写法一
type MyObj = {
  x:number;
  y:number;
};

const obj:MyObj = { x: 1, y: 1 };

// 写法二
interface MyObj {
  x: number;
  y: number;
}

const obj:MyObj = { x: 1, y: 1 };
//写法三

const obj: {
  x: number;
  y: number;
} = { x: 1, y: 1 };

//可选属性
const obj: {
  x: number;
  y?: number;
} = { x: 1 };

//属性名索引类型
type MyObj = {
  [property: string]: string
};
let obj:myObj = {
 'name':'大爷',
 'age':'90',
}
//解构
const {id, name, price}:{
  id: string;
  name: string;
  price: number
} = product;

//never代表字符串属性名是不存在的!不存在 !不存在 !
interface WithoutProperties {
  [key: string]: never;
}

// 报错
const a:WithoutProperties = { prop: 1 };

interface接口

interface Person {
  firstName: string;
  lastName: string;
  age: number;
}
const p:Person = {
  firstName: 'John',
  lastName: 'Smith',
  age: 25
};

interface 的继承

interface Shape {
  name: string;
}

interface Circle extends Shape {
  radius: number;
}

上面示例中,Circle继承了Shape,所以Circle其实有两个属性name和radius。这时,Circle是子接口,Shape是父接口。

interface 继承 type

type Country = {
  name: string;
  capital: string;
}

interface CountryWithPop extends Country {
  population: number;
}

接口合并

interface Box {
  height: number;
  width: number;
}
interface Box {
  length: number;
}

上面示例中,两个Box接口会合并成一个接口,同时有height、width和length三个属性。

相关文章

网友评论

      本文标题:ts

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