簡體   English   中英

打字稿:使用類型斷言后驗證類型

[英]Typescript: validate type after using type assertion

有沒有一種方法可以在使用類型斷言后允許對值進行嚴格的類型檢查?

例如,有時我需要構造一個具有屬性的函數類型:

type FuncPlus = {
    (): void;
    anAttr: number;
    anotherAttr: Array<number>;
};

const f = (() => { }) as FuncPlus;
f.anAttr = 1;

f.anotherAttr.length # will error because `anotherAttr` is `undefined`

我想要一種干凈的構造方法,該構造方法仍可提供實類型安全。

這是我找到的最接近的,但不是很“ typescript-y”:

const f: FuncPlus = Object.assign(
    () => { },
    {
        anAttr: 1,
        // without `anotherAttr` defined here, 
        // typescript will throw a compilation error, as desired
    }
)

有人知道另一種方式嗎?

type FuncPlus = {
  (): void;
  anAttr: undefined | number;
  anotherAttr: undefined | Array<number>;
};

滿足您的條件?

const f = (() => {}) as FuncPlus;

f.anAttr = 1;
f.anAttr.toFixed() // good because of the above assignment

f.anotherAttr = "a" // errors - "a" is not assignable to type
f.anotherAttr.length // still errors // f.anotherAttr may be undefined

f.anotherAttr = []
f.anotherAttr.length // good

Object.assign是分配FuncPlus類型的方式,已經足夠簡潔了。

如果屬性集很少,則可以使用輔助函數來跳過屬性名稱:

const getFuncPlus = (fn: () => void, anAttr: number, anotherAttr: number[]): FuncPlus =>
 Object.assign(fn, { anAttr, anotherAttr });

getFuncPlus(() => {}, 1) // causes an error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM