![](/img/trans.png)
[英]Define JavaScript object literal so that the properties exists for all objects in an array?
[英]Define Type with strings versus object literal properties
我已經傾注了 TS 文檔,但似乎無法找到為什么以下內容是非法的答案。
我可以用字符串定義聯合類型,但是如果我使用 object 屬性的引用創建相同的聯合類型,最終引用相同的字符串值,編譯器就會不高興。
// Success
export type SortOrderWithStrings = 'asc' | 'desc';
export const SortOrderStatic = {
ASC: 'asc',
DESC: 'desc',
}
// Fail
export type SortOrderWithObject = SortOrderStatic.ASC | SortOrderStatic.DESC;
錯誤如下。 為什么這是一個命名空間問題?
Cannot find namespace 'SortOrderStatic'
Exported type alias 'SortOrderReference' has or is using private name 'SortOrderType'
最終,最好有一個Column
接口來定義支持的排序順序類型,然后用SortOrderStatic
實例化一個Column
以避免魔術字符串,但根據上述情況,這似乎是不可能的。
interface Column {
label: string;
defaultSortOrder: SortOrderWithObject;
}
const MyColumn: Column = {
label: 'My Column',
defaultSortOrder: SortOrderStatic.ASC
}
如果我按如下方式定義接口(使用SortOrderWithStrings
),然后嘗試使用SortOrderStatic
,編譯器再次不高興。
interface Column {
label: string;
defaultSortOrder: SortOrderWithStrings;
}
const MyColumn: Column = {
label: 'My Column',
defaultSortOrder: SortOrderStatic.ASC
}
失敗:
Type 'string' is not assignable to type 'SortOrderWithStrings'.
很明顯,我在這里遺漏了一些基本的東西,我很感激任何見解。
很明顯我在這里遺漏了一些基本的東西
是的,您將編譯時與運行時混淆了:除非編譯時類型是文字字符串,否則編譯器無法保證 object 屬性的運行時訪問是您認為的字符串。 您的 object 屬性是string
類型,這意味着在運行時它可以是任何字符串。
字符串文字是不可變的(因此可以靜態驗證),object 屬性訪問量不大。
在您的特定情況下,我將只使用enum :
enum SortOrder {
ASC = 'ASC',
DESC = 'DESC',
}
export { SortOrder }
import { SortOrder } from 'something';
SortOrder.ASC; // ASC as a string
這將保持類型安全,您不能將任何 ol' 字符串傳遞給需要SortOrder
的東西:( Playground )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.