#typescript How can I refine the return type of a function on a class using a type guard?

Rather niche typescript question…

I have a class with a method that returns string | null and I’d like to refine the type of objects of that class in situations where we know the method will return a string.

Here’s a playground example: https://www.typescriptlang.org/play?#code/MYGwhgzhAEASkFkwE8BGBTAcgVxCAYtgHbAAuAlgPZHQDeAUPdNMNRKQE7ZmUcAUABw7kAbmFLpo7YUQDmAeQ448ALimdyc6AB9oRXCACUdJs2ikAFuQgA6aZoVKD0ALzqZj5SFMBfRswBbFAwvQhIKaj5jBjNoDnRSbA4aS2s7DTlFL196P3pSZAFJeAgAZQzZMLIqIgAeABUAPldoeugAMhNmAHpu6CQAa0lLSSC0LAMqiJoAE3QAM01yCRBkPUpSPWdAFAJW2ABJUugAEXkAUSPMeTaAdXkAJQBpUzGQyeJq6jUo12b7OVyjF65kKklk2DAHBm5ko0HQRAgSWGVjkNleEzwUxqP2s602+jw9HmH2m0GsJXKHix1AacIAHhIiDMYCUkONQiSao0+Kk5Gp6oY1LzZGSWZBKQ5qXUml04gkkjQAISK4Vo4IYgicyKGQH0YHE8I1cwWcTQMDAYDoASkGDUVZm9wOAA0ZqZeK2hINnxoRHQ6GZErkmA2Xj4AEdsHS1P9ZNFTKwEZQQOgbCBKLJw5GdXkE+xoPNKLC3L6AO5wRDqjmGyIAcgLlBrOvo5HmfHJ4oqUr49cMcZ6fRuFjWuPravZ72rRB+7HIeEdWl0BJAZvmEg4xuGoOg4MhMwA-KZff6yhVg6RQ6P0VXvVFs4wgA

Anyone know how to do this?

Could you just use the postfix non-null assertion operator !?

foo.maybeNullFunction() can be either null or string , so the compiler can’t conclude which type the returned value is in your example. foo.maybeNullFunction()! asserts the returned value can’t be null, so the compiler concludes it’s a string.