跳到主要内容

类型断言

2023年03月02日
柏拉文
越努力,越幸运

类型断言: 明确的告诉编译器我们要将一种类型指定为另一种类型。TypeScript 提供了两种执行类型断言的语法:

语法

  • 使用圆角括号 <>

    const num:any = 100;
    const nums = <number> num;
  • 使用关键字 as

    const num:any = 100;
    const nums = num as number;

场景

  • 场景一: 通过类型断言,声明可读 as const

    as const 告诉Typescript它所断言的值以及该值的所有层级的子属性都是不可篡改的,故对每一级子属性都会做最严格的类型推断

    • 案例一、as const 用于断言变量

      let a = 3 as const;
      a=4; // Type '4' is not assignable to type '3'

      // 对应于
      const a = 3;
    • 案例二、as const 用于断言数组

      let array = [10,20,30] as const;
      array[0] = 40; // Cannot assign to '0' because it is a read-only property

      // 对应于
      let array:readonly number[] = [10,20,30];
      array[0] = 40; // Index signature in type 'readonly number[]' only permits reading.
    • 案例三、as const 用于断言对象

      let obj = {
      x: 10,
      y: [20, 30],
      z: {
      a:
      { b: 42 }
      }
      } as const;

      // 对应于

      let obj: {
      readonly x: 10;
      readonly y: readonly [20, 30];
      readonly z: {
      readonly a: {
      readonly b: 42;
      };
      };
      };
  • 场景二: 关于 Object.keys()key 操作

    const objct = {
    name:'kk',
    age:23
    }
    const objectKeys = Object.keys(object);
    const objectKeysType = keyof typeof object;
    for(let key of objectKeys){
    const item = objectKeys[key as objectKeysType]
    }
  • 场景三、用于React组件高阶组件传递props

    import React from 'react';

    interface LoaderState {
    data: any;
    loading: boolean;
    }

    interface LoaderProps {
    data: any;
    }

    const withLoader = <P extends LoaderState>(
    WrappedComponent: React.ComponentType<P>,
    url: string,
    ) =>
    class LoaderComponent extends React.Component<LoaderProps, LoaderState> {
    constructor(props: any) {
    super(props);
    this.state = {
    data: null,
    loading: false,
    };
    }

    componentDidMount() {
    this.setState({
    loading: true,
    });
    const ajax = new XMLHttpRequest();
    ajax.open('get', url, true);
    ajax.onreadystatechange = () => {
    if (ajax.readyState === 4 && [200, 304].includes(ajax.status)) {
    const {response} = ajax;
    const data = JSON.parse(response);
    this.setState({
    data,
    loading: false,
    });
    }
    };
    ajax.send();
    }

    render() {
    const {data, loading} = this.state;
    return (
    <div>
    {loading || !data ? (
    <h3>正在请求数据……</h3>
    ) : (
    <WrappedComponent {...(this.props as P)} data={data} />
    )}
    </div>
    );
    }
    };

    export default withLoader;