0

It's pretty hard to explain since I don't know all the terminology yet. But here it goes:

Given the following interface with the optional property 'id'.

interface User {
  id?: string;
  name: string;
}

In some parts of the application the id property is undefined (yet). But at a certain point in my application I know for sure that the id is there.

// at this point user.id is definitely defined
users.map((user: User) => {
  return (<p>{user.name} with the id: {user.id}<p>)
  // TS error: Type 'undefined' is not assignable to type 'string'.
});

Now I can add an 'if' statement to solve this issue. But is there a way that I can 'tell' Typescript that the ID property now is available for sure? Or is that not smart to do...

Ideally I do not want to have to maintain another interface or alias with the id property non-optional.

Remi
  • 4,663
  • 11
  • 49
  • 84
  • Does this answer your question? [In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?](https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) – Harun Yilmaz Sep 25 '20 at 13:17
  • Try changing from ```{user.id}``` to ```{user?.id}```. – Carlo Corradini Sep 25 '20 at 13:27
  • If your are really sure that the `id` is defined, then you can cast it using `{user.id as string}`. But I really recommand you to use an `if` statement instead. – johannchopin Sep 25 '20 at 13:35
  • Thanks guys. I remembered the bang operator. Seems like an elegant solution. ESLint is complaining though, so I accepted Rubydesic's answer. The typecasting was also a good suggestion. Adding the if statement is the wisest to prevent future changes. But having all those if statements makes the code so bloated.. – Remi Sep 25 '20 at 13:39

1 Answers1

0

Change the type of User when you assign the IDs:

interface IdUser extends User {
    id: string
}

function assignId(user: User): IdUser {
    return {...user, id: 'id' };
}
Rubydesic
  • 3,386
  • 12
  • 27