TypeScript 类型学习2

//type与interface的拓展
interface Animal {
  name: string;
}
interface Tiger extends Animal {
  age: number;
}
const tiger: Tiger = { name: "xixi", age: 19 };

//类型别名使用&符号拓展 接口interface使用extends拓展
type Tree = { name: string };

type GreenTree = Tree & { color: string };

const redtree: GreenTree = { name: "redtree", color: "blue" };

//字符串文字类型组合使用
function printText(s: string, alignment: "left" | "right" | "center") {}
printText("hello", "center");

//数字文字类型组合使用
function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}
//console.log(compare("14", "13"));
//数字文字类型组合使用
interface Options {
  width: number;
}
function configure(x: Options | "auto") {}
configure({
  width: 100,
});
configure("auto");

function handleRequest(url: string, method: "GET" | "POST") {}
const req = {
  url: "http://dadsasda",
  method: "GET",
} as const;
handleRequest(req.url, req.method);
//ts会帮助我们类型推断method是string

//两种方法 1.添加类型推断 使用 as 'GET' 2.将req统一变成文字类型或者是const //使用 as const 这样就可以固定类型了
//文字类型在ts中去细化类型很有用

//null和undefined
let un: undefined = undefined;
let nu: null = null;

function doSomthing(x?: number | null) {
  //使用非空断言运算符推断! 一般情况下不使用!
  console.log(x!.toFixed(4));
}

//类型缩小 从宽类型缩小为窄类型 一般用于联合类型
function padLeft(padding: number | string, input: string): string {
  //return new Array(padding + 1).join(" ") + input;  //满足不了我们的业务需求
  if (typeof padding === "number") {
    //ts是严谨的 叠加了很多的类型分析 相当于把类型给缩小了,又叫类型保护。
    return new Array(padding + 1).join(" ") + input;
  }
  return padding + input;
}
//1.typeof 类型守卫  typeof strs==="object" string number boolean   (in 关键字,typeof 关键字 ,instanceof ,自定义类型保护的类型谓词)
//可以理解为缩小不同分支的类型 在项目中我们检查typeof的返回值是一种类型保护,因为ts对typeof进行编码从而返回不同的值
//其主要思想是尝试检测属性、方法或原型,以确定如何处理值

//真值缩小 在js中使用条件、&&、||、if语句、布尔否定(!)
function getUserOnlineMessage(num: number) {
  if (num) {
    return `现在共有${num}人在线`;
  }
  return "现在没有人在线";
}
//这两个结果都返回true
Boolean("hello"); //返回true 注意B大写
!!"world"; //转换的对象前面加!! 返回true
//!可将变量转换成boolean类型,null、undefined和空字符串取反都为true,其余都为false。
//这种使用真值进行类型缩小的方法是比较流行的。

function printAll(strs: string | string[] | null) {
  if (strs && typeof strs === "object") {
    //这里使用&&去真值缩小 这个传的是一个有效的str
    for (const iterator of strs) {
      //这里出现了错误 因为null也是个object
      console.log(strs);
    }
  } else if (typeof strs === "string") {
    console.log(strs);
  } else {
  }
}

//通过布尔否定叹号,把逻辑从否定分支中过滤掉
function multiplyAll(values: number[] | undefined, factor: number) {
  //如果values不存在
  if (!values) {
    return values;
  } else {
    return values.map((x) => {
      return x * factor;
    });
  }
}
console.log(multiplyAll([3, 4], 2));

//等值缩小 === !== == != 来使用等值缩小
function example(x: string | number, y: string | undefined) {
  if (x === y) {
    //因为xy都有string类型 所以ts可以推断出来
    x.toUpperCase();
    y.toLowerCase();
  } else {
    console.log(x);
    console.log(y);
  }
}

// strs !== null 来缩小范围
function printAll2(strs: string | string[] | null) {
  if (strs !== null) {
    if (typeof strs === "object") {
      //这里使用&&去真值缩小 这个传的是一个有效的str
      for (const iterator of strs) {
        //这里出现了错误 因为null也是个object
        console.log(strs);
      }
    } else if (typeof strs === "string") {
      console.log(strs);
    } else {
    }
  }
}
printAll2(null);

//判断某个变量是否等于null 和 undefined
interface Container {
  value: number | null | undefined;
}
function multiplyValue(con: Container, factor: number) {
  if (con.value != null) {
    console.log(con.value);
    con.value *= factor;
  }
}
multiplyValue({ value: 5 }, 6);
multiplyValue({ value: undefined }, 6);
multiplyValue({ value: null }, 6);

  

posted @ 2022-04-06 15:36  葫芦娃啊  阅读(4)  评论(0编辑  收藏  举报