TypeScript随笔

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);
};

posted @ 2021-01-01 10:10  老胡Andy  阅读(81)  评论(0编辑  收藏  举报