打字稿:可选字段和未定义的联合有什么区别? [英] Typescript: What's the difference between an optional field and a union with undefined?

查看:19
本文介绍了打字稿:可选字段和未定义的联合有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个带有可选字段的接口.我认为以下是同义词.

I want to define an interface with optional fields. I thought the following were synonymous.

(A):

interface State {
  userDetails: undefined | string | DataStructure | Error;
}

(B):

interface State {
  userDetails?: string | DataStructure | Error;
}

但是当我去初始化状态时,(A) 强制我将字段显式设置为未定义,如下所示:

But when I go to initialise the state, (A) forces me to explicitly set the field as undefined, like so:

static readonly initialAppState: AppState = {
  userDetails: undefined
};

但是使用 (B) 我可以完全省略该字段:

But with (B) I can just omit the field completely:

static readonly initialAppState: AppState = { };

如果我在使用定义时尝试省略该字段 (A) Typescript 会抱怨说:

If I try to omit the field when using definition (A) Typescript will complain saying:

Property 'userDetails' is missing in type

为什么在使用定义 (A) 时必须显式设置字段?在初始化时强制这种不同要求的两个定义之间有什么区别?

Why do I have to set the field explicitly when using definition (A)? What's the difference between the two definitions that forces this different requirement when initialising?

打字稿版本:2.3.4

Typesript version: 2.3.4

编辑:如果您发现这个问题和下面的答案有趣或相关,您可能想知道 TypeScript 在 v4.4 中正在更改以添加 --exactOptionalPropertyTypes 标志.这个新标志现在会导致一些原始代码出现错误,促使我提出这个问题.

Edit: If you found this question and the answer below interesting or relevant, you may want to know that TypeScript is changing in v4.4 to add the --exactOptionalPropertyTypes flag. This new flag will now cause an error on some of the original code that prompted me to ask this question.

推荐答案

即使在运行时,具有未定义值的键和不存在的键之间也存在差异.TypeScript 允许区分并不奇怪.

Even at runtime there is a difference between a key with an undefined value and a key that doesn't exist. That TypeScript allows differentiating is not surprising.

试试这个:

Object.keys({a: undefined});

如果离开 a 并将其值设置为 undefined 是同一件事,那么我们希望上面的内容返回一个空数组,但实际上它返回

If leaving a out and setting it's value to be undefined were the same thing then we'd expect the above to return an empty array, but in fact it returns

[ 'a' ]

这篇关于打字稿:可选字段和未定义的联合有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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