【问题标题】:What is HasValue and .Value equivalent in TypeScript什么是 TypeScript 中的 HasValue 和 .Value 等价物
【发布时间】:2022-01-11 13:25:22
【问题描述】:

我有一个方法:

public cancelOperation(OperationId: string): Promise<void> 
 {
         // some calls
 }

我从另一个方法获得 OperationId:

let operationId = GetOperationId() {}

返回可为空的 OperationId,

 operationId?: string;

所以当传递从 GetOperationId() 接收到的 OperationId 时,我收到 operationId 可以为空的错误,因此不能在方法 cancelOperation() 中使用

那么有没有 C# 等价于

 operationId .Value 

operationId .HasValue 

Typescript 中的方法,所以我可以去做。

虽然我们可以选择检查 operationId,例如:

 cancelOperation(playAudioResult.operationId ? playAudioResult.operationId : "")

但我不想使用它。

我需要一个类似的解决方案: cancelOperation(operationId.?????)

【问题讨论】:

  • let operationId = GetOperationId() {} 看起来语法不正确。
  • @ShamPooSham 好的,我已经改了
  • 你没有改变我说的那一行
  • 但是如果你的意思是operationId的类型是string | undefined,如果你在@987654333中调用cancelOperation,打字稿会很聪明地从类型中删除| undefined @
  • 没有,因为 typescript 和 C# 以非常不同的方式工作。但我认为这实际上做了同样的事情:如果定义了值,它将被使用。您还可以使用非空断言运算符 (!) typescriptlang.org/docs/handbook/release-notes/…

标签: javascript c# typescript conditional-operator null-check


【解决方案1】:

if (operationId) 将在 TypeScript 中检查 null。 如果值不是nullundefined,它将返回true

【讨论】:

  • 这很好,但我们正在寻找 .Value 等价物
  • 你为什么需要它?它只会增加另一层抽象。
【解决方案2】:

你可以使用 if 来检查 operationI 是否为空。另一种方法是无效的合并运算符。

它是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数。

只有当值不为空时才会执行,

let x = operationI??NULL

【讨论】:

  • 这是另一个操作,不会在方法中单独执行
【解决方案3】:

关注@ShamPooSham 分享的文章 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator

如文章中所述,我有一种方法可以从可为空的属性中获取值。

我们需要放 !在属性之后并获取值(假设它不为空)

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
  // Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
 validateEntity(e);
 let s = e!.name; // Assert that e is non-null and access name
}

我可以使用的方法类似:

cancelOperation(playAudioResult.operationId!)  // notice the !

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2020-08-16
    • 2013-07-01
    • 2014-05-08
    相关资源
    最近更新 更多