如何告诉 TypeScript 对象中的可选属性存在并已设置?

2024-04-25

我有以下代码:

interface First
{
  propertyA: string;
}

// Here propertyA is optional
// Imagine that this interface came from external library.
interface Second
{
  propertyA ?: string;
}

function fn(arg: First)
{
  // ...
}

// I know that this object can be declared as type of First,
// but I really need set this as type of Second interface
let myVar: Second = {propertyA: 'some string'};

// I really need in this way to make the call.
fn(myVar); // Error

if(myVar.hasOwnProperty('propertyA'))
{
  fn(myVar); // Still same error
}

if(myVar.propertyA)
{
  fn(myVar); // Still same error
}

但是 TypeScript 抛出错误:

“Second”类型的参数不可分配给“First”类型的参数。 属性“propertyA”在类型“Second”中是可选的,但在类型“First”中是必需的。

那么,如何告诉 TypeScript 可选属性propertyA in myVar是否存在并已设置?


老问题,但在新版本的打字稿中有一个非常干净的解决方案

fn(myVar!);

在 Typescript 中,什么是 !取消引用成员时使用(感叹号/爆炸)运算符? https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci

编辑: 这并没有回答OP想要告诉Typescript propertyA是在myVar内部定义的原始问题。该解决方案因误导性标题而存在偏差,它仅显示如何指示 Typescript 定义给定的 var (myVar!) 或属性 (myVar.propertyA!)。

看来很多人都是看到标题才来到这里的,并发现这个答案很有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何告诉 TypeScript 对象中的可选属性存在并已设置? 的相关文章

随机推荐