码迷,mamicode.com
首页 > 其他好文 > 详细

TypeScript随笔

时间:2021-01-05 10:50:47      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:network   The   类型检查   default   known   dex   row   message   类型   

1: any 和 unknown类型的区别
any可以避开类型检查, 比如
let notSure: any = ‘XXXXX‘;
notSure.Hello();

unknown在使用时必须进行类型断言:
let x: unknown = ‘xxxxxx‘;
console.log((x as string).toLowerCase());

2:以下接口中的第三行表示该接口除了color和width外,还可以接受任何类型的参数
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}

3:Indexable Types
interface StringArray {
[index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

4:联合类型只能访问其公共属性
interface Bird {
fly(): void;
layEggs(): void;
}

interface Fish {
swim(): void;
layEggs(): void;
}

declare function getSmallPet(): Fish | Bird;

let pet = getSmallPet();
pet.layEggs();

// Only available in one of the two possible types
pet.swim();

5:never的一个使用场景
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}

function logger(s: NetworkState): string {
switch (s.state) {
case "loading":
return "loading request";
case "failed":
return failed with code ${s.code};
case "success":
return "got response";
default:
return assertNever(s);
Argument of type ‘NetworkFromCachedState‘ is not assignable to parameter of type ‘never‘.
}
}

6: 联合类型 (union type) 和 交叉类型 (intersection type)
联合类型:只能访问两个类型的公共部分

interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs(): void;
}

declare function getSmallPet(): Fish | Bird;

let pet = getSmallPet();
pet.layEggs();

// Only available in one of the two possible types
pet.swim();

交叉类型:组合两个类型的所有属性


interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtworksData {
  artworks: { title: string }[];
}

interface ArtistsData {
  artists: { name: string }[];
}

// These interfaces are composed to have
// consistent error handling, and their own data.

type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;

const handleArtistsResponse = (response: ArtistsResponse) => {
  if (response.error) {
    console.error(response.error.message);
    return;
  }

  console.log(response.artists);
};

TypeScript随笔

标签:network   The   类型检查   default   known   dex   row   message   类型   

原文地址:https://www.cnblogs.com/Andy1982/p/14218756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!