openlang

How can TypeScript accept an object with no properties?

This is the code.

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

The error I receive says The property "label" does not exist in the type "{} | {label: string;}".The property "label" does not exist in the type "{}".

I'm a typescript beginner. How can I declare that item accepts either an empty object or {label: string}.

The conversation continues 2

Follow the reasoning
  1. Permalink

    Make the label property optional by adding ?:

    function inspect(item: { label?: string }) {
        if (item.label) {
            console.log("inspect jingo");
        }
    }
  2. Permalink

    I'm unsure whether TypeScript considers this a good approach, but inside your if condition you can explicitly assert that item has the type { label: string }:

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

Other sides of the same question

  1. TypeScript Map initialization with string array entries

    I'm creating a Map whose entries each hold an array of strings. How can I declare its type and initialize it together in one…

    Replies 2Latest activity typescript
  2. Typescript Callable Contract

    Why does Typescript accept my function definition even though it differs from the interface signature, yet report a problem w…

    Replies 2Latest activity typescript
  3. Solidity conversion failure from address into uint256

    I made an array containing structs, then attempted to retrieve each account's values from that array. But passing an address…

    Replies 3Latest activity solidity