且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类型联合不检查多余的属性

更新时间:2023-11-29 15:21:58

在联合如何与多余的属性检查结合工作方面,这有点奇怪.{A:1, C: 3} 实际上与 {C: number} 兼容,除了额外的属性检查:

const o = {A:1, C: 3};const ok: {C: number} = o;//没有直接的文字赋值,没有多余的属性检查const nok: {C: number} = { A:1, C: 3};//多余的属性检查开始

游乐场链接

如果工会有很多成员,您也可以使用 此处 中的 StrictUnion

类型 UnionKeys<T>= T 扩展 T ?keyof T : 从不;输入 StrictUnionHelper;= T 扩展任何 ?与Partial<Record<Exclude<UnionKeys<TAll>,keyof T>,从不>>: 绝不;输入 StrictUnion= StrictUnionHelpertype T = StrictUnion;const 有效:T = {A: 1, B: 2};const 也有效:T = {C: 3};//错误const 无效:T = {A: 1, B: 2, C: 3};//错误const 也无效:T = {A:1, C: 3};

游乐场链接

let's imagine a have an object that either have properties A and B or C, e.g.:

const temp = {
  A: 1,
  B: 2,
}

or

const temp = {
  C: 3,
}

And intuitively I see this type as:

type T =  {A: number, B: number} | {C: number};

const valid: T = {A: 1, B: 2};
const alsoValid: T = {C: 3};

// Should complain but it does not
const invalid: T  = {A: 1, B: 2, C: 3};
// Also should complain
const alsoInvalid: T = {A:1, C: 3};

But TS treats such type as {A?: number, B?: number, C?: number} and basically | makes fields optional but I want TS to complain about inconsistent type when I add C property to A and B


How can I archive the desirable type?

This is a bit of a quirk in how unions work in conjunction with excess property checks. {A:1, C: 3} is actually compatible with {C: number} except for excess property checks:

const o = {A:1, C: 3};
const ok: {C: number} = o; // No direct literal assignment, no excess property checks
const nok: {C: number} = { A:1, C: 3}; // Excess property checks kick in 

Playground Link

And the quirk of excess property checks is that for unions, it allows any property from any union constituent to be present in the assigned object literal.

You can get an error if the union constituents are incompatible one with another:

type T =  {A: number, B: number} | {C: number, A?: undefined, B?: undefined };

const valid: T = {A: 1, B: 2};
const alsoValid: T = {C: 3};

// Error
const invalid: T  = {A: 1, B: 2, C: 3};
//Error
const alsoInvalid: T = {A:1, C: 3};

Playground Link

You can also use the StrictUnion from here if the union has a lot of memebers


type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends any ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>

type T =  StrictUnion<{A: number, B: number} | {C: number }>;

const valid: T = {A: 1, B: 2};
const alsoValid: T = {C: 3};

// Error
const invalid: T  = {A: 1, B: 2, C: 3};
//Error
const alsoInvalid: T = {A:1, C: 3};

Playground Link