openlang

如何让 TypeScript 接受没有属性的对象?

代码如下。

function inspect(item: { label: string } | {}) {
    if (item.label) { //error
        console.log("inspect jingo");
    }
}

我得到的错误是 The property "label" does not exist in the type "{} | {label: string;}".The property "label" does not exist in the type "{}".

我是 typescript 新手。怎样声明 item 能接受空对象或 {label: string}。

从英语翻译查看原文

后续讨论 2

顺着彼此的依据读下去
  1. 固定链接

    加上 ?,把 label 属性设为可选。

    function inspect(item: { label?: string }) {
        if (item.label) {
            console.log("inspect jingo");
        }
    }
    从英语翻译查看原文
  2. 固定链接

    不确定这在 TypeScript 中算不算好办法,但可以在 if 条件中明确断言 item 的类型为 { label: string }。

    function inspect(item: { label: string } | {}) {
        if ((item as {label: string}).label) {
            console.log("inspect jingo");
        }
    }
    从英语翻译查看原文

同一个问题的其他角度

  1. 初始化以字符串数组为值的 TypeScript Map

    我在创建一个 Map,其中每个条目都保存字符串数组。怎样在一条语句中同时声明类型并完成初始化? 我(天真地)这样试了一下。 结果是下面这个错误。

    回复 2最近活动 typescript
  2. Typescript 可调用函数的约定

    为什么 Typescript 接受我的函数定义,虽然它与接口签名不同,但当我实际调用同一个函数时却报告问题。

    回复 2最近活动 typescript
  3. Solidity 从 address 转换为 uint256 时失败

    我创建了一个包含结构体的数组,然后尝试从该数组取得每个账号的值。但传入包含 msg.sender 的 address 变量时失败了,因为它的类型似乎无法转换为 uint256。应该怎样实现?

    回复 3最近活动 solidity