typescript類型記錄

基礎(chǔ)屬性類型

type AppProps = {

  message: string

  count: number

  disabled: boolean

  /** array of a type! */

  names: string[]

  /** string literals to specify exact string values, with a union type to join them together */

  status: 'waiting' | 'success'

  /** 任意需要使用其屬性的對象(不推薦使用,但是作為占位很有用) */

  obj: object

  /** 作用和`object`幾乎一樣,和 `Object`完全一樣 */

  obj2: {}

  /** 列出對象全部數(shù)量的屬性 (推薦使用) */

  obj3: {

    id: string

    title: string

  }

  /** array of objects! (common) */

  objArr: {

    id: string

    title: string

  }[]

  /** 任意數(shù)量屬性的字典,具有相同類型*/

  dict1: {

    [key: string]: MyTypeHere

  }

  /** 作用和dict1完全相同 */

  dict2: Record<string, MyTypeHere>

  /** 任意完全不會調(diào)用的函數(shù) */

  onSomething: Function

  /** 沒有參數(shù)&返回值的函數(shù) */

  onClick: () => void

  /** 攜帶參數(shù)的函數(shù) */

  onChange: (id: number) => void

  /** 攜帶點(diǎn)擊事件的函數(shù) */

  onClick(event: React.MouseEvent<HTMLButtonElement>): void

  /** 可選的屬性 */

  optional?: OptionalType

}

type,interface

  interface PointX {
    x: number
  }

  interface Point extends PointX {
      y: number
  }
  // 類型繼承
  type PointX = {
    x: number
  }

  type Point = PointX & {
      y: number
  }
  // 接口繼承類型
  type PointX = {
    x: number
  }
  interface Point extends PointX {
      y: number
  }
  // 類型繼承接口
  interface PointX {
    x: number
  }
  type Point = PointX & {
      y: number
  }
// 共同點(diǎn):1,都可以定義對象類型。2,都可以繼承擴(kuò)展。
// 不同點(diǎn):1,type 可以為基本類型,聯(lián)合類型,元組,any。
//    2,interface 定義重名了會合并屬性,type 辦不到(會報(bào)錯提醒 重復(fù)定義)。

React 屬性類型

export declare interface AppBetterProps {

  children: React.ReactNode // 一般情況下推薦使用,支持所有類型 Great

  functionChildren: (name: string) => React.ReactNode

  style?: React.CSSProperties // 傳遞style對象

  onChange?: React.FormEventHandler<HTMLInputElement>
  
}
  // useState 對象
  const [user, setUser] = React.useState<IUser>({} as IUser);

export declare interface AppProps {

  children1: JSX.Element // 差, 不支持?jǐn)?shù)組

  children2: JSX.Element | JSX.Element[] // 一般, 不支持字符串

  children3: React.ReactChildren // 忽略命名,不是一個合適的類型,工具類類型

  children4: React.ReactChild[] // 很好

  children: React.ReactNode // 最佳,支持所有類型 推薦使用

  functionChildren: (name: string) => React.ReactNode // recommended function as a child render prop type

  style?: React.CSSProperties // 傳遞style對象

  onChange?: React.FormEventHandler<HTMLInputElement> // 表單事件, 泛型參數(shù)是event.target的類型

}

關(guān)鍵字段解釋

Record

創(chuàng)建一個類型

type Coord = Record<'x' | 'y', number>
// 等同于
type Coord = {
  x: number,
  y: number
}
Partial

將類型定義的所有屬性改為可選

type Coord = Partial<Record<'x' | 'y', number>>
// 等同于
type Coord = {
  x?: number,
  y?: number
}
Readonly

將所有屬性定義為自讀

Pick

從類型定義的屬性中,選取指定一組屬性,返回一個新的類型定義

type Coord = Record<'x' | 'y', number>;
type CoordX = Pick<Coord, 'x'>;

// 等用于
type CoordX = {
    x: number;
}

interface IPorps<T> {
  tableProps: Pick<TableProps<T>, keyof TableProps<T>>;
}

Omit

去除接口中某個值,對接口做剪裁

interface Foo {
    a: number;
    b: string;
    c: boolean;
}

// { a:number; }
type OnlyA = Pick<Foo, "a">;

type ExcludeA = Omit<Foo, "a"> // { b: string; c: boolean}
extends

條件類型

// x是y ? true : false
type Equal<x, y> = x extends y ? true : false
type Num = <1, 1>  // true

// T是number類型 ? number : string
type IsNum<T> = T extends number ? number : string

type Num = IsNum<1>   // number;
type Str = IsNum<'1'> // string;
keyof

類型對象,返回key組成的聯(lián)合類型

type Dog = { name: string; age: number;  };
type D = keyof Dog; // type D = "name" | "age"
typeof

提供對象的類型

const bmw = { name: "BMW", power: "1000hp" }
type bmwType = typeof bmw // { name: string, power: string }
enum

會被編譯成對象使用

enum obj {
    name = "前端娛樂圈",
    num = 100
}
infer

用在extends語句后表示待推斷的類型,用它取到函數(shù)返回值的類型

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
type Str = ReturnType<(x: string) => string> // type Str = string

斷言

類型斷言好比其他語言里的類型轉(zhuǎn)換

尖括號 <>
let a: any = "this is a string";
let strLength: number = (<string>a).length; // a 是any類型 使用<>轉(zhuǎn)成string
as
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

style={{['--bg_color' as any]: 'red'}}
非空斷言 !

排除 null和undefined

1,忽略 undefined 和 null 類型
function myFunc(maybeString: string | undefined | null) {
  // Type 'string | null | undefined' is not assignable to type 'string'.
  // Type 'undefined' is not assignable to type 'string'. 
  const onlyString: string = maybeString; // Error
  const ignoreUndefinedAndNull: string = maybeString!; // Ok
}

2, 調(diào)用函數(shù)時忽略 undefined 類型
type NumGenerator = () => number;

function myFunc(numGenerator: NumGenerator | undefined) {
  // Object is possibly 'undefined'.(2532)
  // Cannot invoke an object which is possibly 'undefined'.(2722)
  const num1 = numGenerator(); // Error
  const num2 = numGenerator!(); //OK
}

// 確定賦值斷言 !
let x!: number;
initialize();
console.log(2 * x); // Ok,沒加!時會報(bào)錯: // Variable 'x' is used before being assigned.(2454)

function initialize() {
  x = 10;
}


參考來源: https://juejin.cn/post/6952696734078369828

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容