簡體   English   中英

如何覆蓋打字稿中的屬性?

[英]How do I override a property in typescript?

由於當前的語言限制,這可能是不可能的,但我使用的是最新的 TS (1.8.10),並且遇到了 ui-grid 類型的問題。 IGridOptions上的isRowSelectable屬性被定義為一個可選的布爾值,但文檔說它是一個函數(確實如此)。 我正在嘗試將布爾屬性覆蓋為返回布爾值的函數。

通常,我只是擴展打字界面並做我需要的事情,但在這種情況下這不起作用。 這是我所擁有的:

interface ISelectionGridOptions extends IGridOptions {
  isRowSelectable: (row: IGridRowOf<Profile>) => boolean;
}

IGridOptions中的相關字段是:

export interface IGridOptions {
  ...
  isRowSelectable?: boolean
  ...
}

我得到的錯誤是:

(41,11): error TS2430: Interface 'ISelectionGridOptions' incorrectly extends interface 'IGridOptionsOf<any>'.
  Types of property 'isRowSelectable' are incompatible.
    Type '(row: IGridRowOf<Profile>) => boolean' is not assignable to type 'boolean'.

沒有修復核心類型定義,有沒有辦法在我的代碼中解決這個問題?

您可以使用實用程序類型Omithttps ://www.typescriptlang.org/docs/handbook/utility-types.html#omittk

interface ISelectionGridOptions extends Omit<IGridOptions, 'isRowSelectable'> {
  isRowSelectable: (row: IGridRowOf<Profile>) => boolean;
}

如果類型定義不正確,則不能使用覆蓋來修復它們 - 類型系統正確地將其視為錯誤。 在類型化語言中,防止子類更改類型簽名是一件好事。 這里的問題是損壞的類型定義。 如果修復 def 不切實際,並且問題僅出現在代碼中的幾個地方,則可以使用強制轉換為any來禁用類型檢查,直到修復 defs:

var foo = <boolean> (<any>bar).isRowSelectable(args);
bar.isRowSelectable = <any>foo; 

只需發表評論,解釋發生了什么。 當然,最好修復類型 defs。

注意:它會中斷,就像錯誤所說的那樣,因為函數不能分配給布爾值。 函數 peg 無法裝入布爾孔,反之亦然

TS 3.5+ 的更新

您可以將此實用程序類型添加到您的項目中:

type Modify<T, R> = Omit<T, keyof R> & R;

然后像這樣使用它:

type ISelectionGridOptions = Modify<IGridOptions, {
  isRowSelectable: (row: IGridRowOf<Profile>) => boolean;
}>

TS Playground 中的演示

延伸閱讀

您可以使用優秀的type-fest包中的Merge實用程序來覆蓋或覆蓋類型上的任何屬性,無論它是原始類型:

import type {Modify} from 'type-fest'

type SelectionGridOptions = Modify<GridOptions, {
  isRowSelectable: (row: GridRow<Profile>) => boolean;
}>

暫無
暫無

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

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