簡體   English   中英

在 TypeScript 中定義一個空對象類型

[英]Define an empty object type in TypeScript

我正在尋找定義不能保存任何值的空對象類型的方法。

type EmptyObject = {}

const MyObject: EmptyObject = {
  thisShouldNotWork: {},
};

具有該類型的對象可以自由添加任何屬性。 如何強制MyObject始終為空對象?

我的實際用例是在接口內使用 EmptyObject 類型。

interface SchemaWithEmptyObject {
  emptyObj: EmptyObject; 
}
type EmptyObject = {
    [K in any] : never
}

const one: EmptyObject = {}; // yes ok
const two: EmptyObject = {a: 1}; // error

我們在這里要說的是EmptyObject的所有最終屬性都只能是never ,並且由於never沒有代表值,因此創建這樣的屬性是不可能的,因此對象將保持為空,因為這是我們創建它的唯一方法沒有編譯錯誤。

type EmptyObject = Record<any, never>

這相當於Maciej Sikora 的答案,但使用了Record 實用程序類型

根據 VSC type emtyObj = Record<string, never>

定義空對象類型有幾個選項,它完全取決於您在訪問或設置屬性時想要的關於 linter 和 typescript 錯誤的副作用。 這些是我嘗試過的選項:

// Option A:
let objA: Record<any, never> = {}; // Typescript-ESLint error: Unexpected any. Specify a different type.
objA = { prop: 'value' }; // Typescript error: Type 'string' is not assignable to type 'never'.
console.log(objA.prop);
console.log(objA.nonExistingProp); // No error!!!

// Option B:
let objB: Record<string, never> = {};
objB = { prop: 'value' }; // Typescript error: Type 'string' is not assignable to type 'never'.
console.log(objB.prop);
console.log(objB.nonExistingProp); // No error!!!

// Option C:
let objC: Record<never, never> = {};
objC = { prop: 'value' };
console.log(objC.prop); // Typescript error: Property 'prop' does not exist on type 'Record<never, never>'
console.log(objC.nonExistingProp); // Typescript error: Property 'nonExistingProp' does not exist on type 'Record<never, never>'.

TLDR: Record<string, never>在將屬性設置為空對象時引發錯誤。 Record<never, never>在訪問空對象的屬性時引發錯誤。 我還沒有找到在這兩種情況下都會引發錯誤的解決方案。

就我個人而言,我為當前的用例選擇了選項 C,因為我希望在嘗試訪問空對象的屬性時發生錯誤,但您可能不希望這樣!

像這樣帶有私有符號的東西怎么樣?

// EmptyType.ts
const EMPTY_SYMBOL = Symbol();
export type EmptyType = {[EMPTY_SYMBOL]?: never};

它適用於交叉聯合類型。

import {EmptyType} from "./EmptyType";
type Union = EmptyType | { id: string };
const a: Union = {};
const b: string = a.id; // <-- error

打字稿游樂場

暫無
暫無

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

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