0

Let's say I define an interface like this

interface User {
  name: string;
  address?: SomeObject;
}

Later in the code I definitely define it through some dynamic process. Because I can't/don't want to initially define it with a dummy object.

Then I want to use it like this in a function

const foo=(name:string, address: SomeObject)=>{
   console.log(address);
}

If I use it like this

foo(user.name, user.address)

I will get that param2 is possibly undefined.

If I do it like this

const foo=(name:string, address?: SomeObject)=>{
   console.log(address);
}

Then I can call the function but I would have to check inside the function body whether address is defined.

What I want to know if I can to is something like this

const foo=(name:string, address: SomeObject)=>{
       console.log(address);
    }
foo(user.name, user.address!) //where ! is a made up operator that says this object is definitely defined.

tldr: I want to know if there is a way to say to TS that this possibly undefined value is certainly defined by this time of execution.

Syarx
  • 69
  • 1
  • 8
  • [`Required`](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype)? – VLAZ Aug 05 '21 at 11:06
  • @VLAZ no that wouldn't solve it. – Syarx Aug 05 '21 at 11:09
  • 1
    Then I don't know what you need. You say `!` is made up operator [but seems to be exactly what you need](https://www.typescriptlang.org/play?ssl=10&ssc=2&pln=11&pc=1#code/JYOwLgpgTgZghgYwgAgMoHsC2EDyAjAKwgTGQG8BYAKGVuQA8AuZEAV0z2gG5qBfa0JFiIUAVQDO0ctTos42ZuLBRQAcx406cACbaoEceID8zDNnxESG-lQToQS5DHTpkAXmQAKEPIiLlagA0yDp6BuKmWLiExGAAlO4AfNKatHYO6AA2EAB0meiqnqH6hnHW1NTaxJlw+sjpjqySUMwS3BVUzuieTdA5PtjBvVA5xeEAhGVAA). I was struggling to find a different way to do the same without `!`. Can you explain what the problem is with the non-null assertion? – VLAZ Aug 05 '21 at 11:20
  • I swear to god I looked everywhere for this and did not find it and i just assumed i doesn't exist. Thank you for answering! – Syarx Aug 05 '21 at 11:23
  • 1
    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) – VLAZ Aug 05 '21 at 11:25

0 Answers0