是否可以定义一个总是应用额外属性检查的接口/类型? [英] Is it possible to define an interface/type to which excess property checks are always applied?

查看:24
本文介绍了是否可以定义一个总是应用额外属性检查的接口/类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript 中,多余的属性检查应用于对象字面量,但不会超出此范围.(这是故意的记录的行为.)所以给定:

In TypeScript, excess property checks are applied to object literals, but not beyond that. (This is intentional documented behavior.) So given:

interface Example {
    id: number;
    name: string;
}
// ...
function doSomething(ex: Example) {
    // ...
}

此失败(游乐场链接):

doSomething({
    id: 42,
    name: "Life, the Universe, and Everything",
    extra: "not allowed" // Error 2345: Object literal may only specify known properties, and 'extra' does not exist in type 'Example'.
});

但这并不(

const ex = {
    id: 42,
    name: "Life, the Universe, and Everything",
    extra: "not allowed"
};
doSomething(ex);

是否可以以某种方式定义接口,即使不使用对象字面量也禁止过多的属性?例如,某种final"接口?

Is it possible to define the interface in some way that excess properties are forbidden even when not using an object literal? E.g., a "final" interface of sorts?

如果没有,在运行时很容易完成,但如果有一种方法可以在类型定义中完成,那将会很有用.

If not, it's easily done at runtime, but if there's a way to do it in the type definition, that would be useful.

推荐答案

您正在寻找的是精确类型.此功能一直在讨论 GH 上的讨论,但它并没有更接近实际上正在实施.令人担忧的是(至少从我在 tsConf 上从 Anders 那里听到的)是精确类型会创建一个分叉的类型系统,在那里你不能从精确到不精确的类型和向后分配,这会使开发体验变得更糟.

What you are looking for is exact types. This feature has been in discussion since forever on GH but it has not come any closer to actually being implemented. The concern is (at least from what I heard at tsConf from Anders) is that exact types would create a bifurcated type system, where you could not assign from exact to inexact types and backwards, and this would make the dev experience much worse.

有一些变通方法,但都在某些方面存在缺陷,您可以阅读 GH 问题以找到各种可能运行良好的版本,具体取决于您尝试执行的操作.

There are work arounds, but all are flawed in some way, you can read the GH issue to find all sorts of versions that might work well enough depending on what you are trying to do.

这篇关于是否可以定义一个总是应用额外属性检查的接口/类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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