是否可以选择严格传播对象? [英] Is there an option to make spreading an object strict?

查看:20
本文介绍了是否可以选择严格传播对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有编译器选项或类似的东西可以使传播对象严格.

请看下面的例子来理解我的意思:

interface Foo {a:字符串;}界面栏{a:字符串;b:数量;}const barObject: Bar = { a: "a string", b: 1 };//应该给出警告,因为 Bar 比 Foo 有更多的属性(这里是 b)const fooObject: Foo = { ...barObject };//实际上打印 1console.log((fooObject as any).b);

这样的事情有可能吗?

解决方案

有趣的问题.根据这个问题,价差运算符的结果旨在 触发过多的属性检查.

<预><代码>//barObject 的 props 比 Foo 多,但 spread 不会触发过多的属性检查const fooObject: Foo = { ...barObject };//b 是显式属性,因此这里开始检查const foo: Foo = { ...bar, b: 2 }

TypeScript 目前没有确切类型,但您可以创建一个简单的类型检查以强制执行严格的对象传播:

//返回 T,如果 T 和 U 匹配,否则从不类型 ExactType= T 扩展 U ?U 扩展 T ?T:从不:从不const bar: Bar = { a: "a string", b: 1 };const foo: Foo = { a: "foofoo" }const fooMergeError: Foo = { ...bar as ExactType};//错误const fooMergeOK: Foo = { ...foo as ExactType};//好的

通过辅助函数,我们可以减少一点冗余:

const enforceExactType = () =><T>(t:ExactType<T,E>) =>吨const fooMergeError2: Foo = { ...enforceExactType()(bar) };//错误

代码示例

I was wondering if there is a compiler option or something similar to make spreading objects strict.

Please see following example to understand what I mean:

interface Foo {
  a: string;
}

interface Bar {
  a: string;
  b: number;
}

const barObject: Bar = { a: "a string", b: 1 };

// should give a warning because Bar has more properties (here b) than Foo
const fooObject: Foo = { ...barObject };

// actually prints 1
console.log((fooObject as any).b); 

Is something like this possible?

解决方案

Interesting question. According to this issue, the result of the spread operator is intended to not trigger excess property checks.


// barObject has more props than Foo, but spread does not trigger excess property checks
const fooObject: Foo = { ...barObject };

// b is explicit property, so checks kicks in here
const foo: Foo = { ...bar, b: 2 }

There aren't exact types for TypeScript currently, but you can create a simple type check to enforce strict object spread:

// returns T, if T and U match, else never
type ExactType<T, U> = T extends U ? U extends T ? T : never : never

const bar: Bar = { a: "a string", b: 1 };
const foo: Foo = { a: "foofoo" }

const fooMergeError: Foo = { ...bar as ExactType<typeof bar, Foo> }; // error
const fooMergeOK: Foo = { ...foo as ExactType<typeof foo, Foo> }; // OK

With a helper function, we can reduce redundancy a bit:

const enforceExactType = <E>() => <T>(t: ExactType<T, E>) => t

const fooMergeError2: Foo = { ...enforceExactType<Foo>()(bar) }; // error

Code sample

这篇关于是否可以选择严格传播对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆