SharePointBeginner
SharePointBeginner

Reputation: 359

Type string | null "possibly null" even after if-checks and null assertion not allowed

I have a variable defined as:

let filter: string | null;

I then try to use it:

filter = "my query";
let translatedStatesName = ["query", "my"];

if(filter) {
    const getFullWordfromQuery = translatedStatesName.filter((a) => a.toLowerCase().
        includes(filter.toLowerCase()));
}

The compiler will complain that filter is "possibly null" even after the if-check, probably due to its type. Due to internal coding guidelines I _cannot_use null assertion such as:

filter!

How to solve it without using null assertion? Playground: https://www.typescriptlang.org/play?ssl=8&ssc=2&pln=2&pc=1#code/DYUwLgBAZglsYgE4C4IGcyJgOwOYQB8JsBXYYAbgFgAoWeJCAXggCIBbATwgEcSlOrajVCRMAQ2xpg4hABMAymFkg0AOXHsQzCAG1WfAawA0bLqwC6w2jCgAKegkQBKCAG9aELxADGAeylIXHAAMTJgAHU-RDkoRD92AEV+RG4WCSkZeSUVdU0QADpHJDs7cVcmAD4IcQKwPwAZPwB3JABhcTQQO2cCz28BnB9gEjlVBzgnOsaW9s7u50XhAF9aWgB6ddJyGrQuxDAYAOhJpABCYj9IcXJZuSA

Upvotes: 0

Views: 104

Answers (2)

Arsen
Arsen

Reputation: 372

Try to store lower case of filter in a variable

if(filter) {
    let toLowerCaseFilter = filter.toLowerCase();
    const getFullWordfromQuery = translatedStatesName.filter((a) => a.toLowerCase().includes(toLowerCaseFilter));
}

Upvotes: 1

Lesiak
Lesiak

Reputation: 26066

TS doesn't know when the arrow function is called, filter can be modified at that time.

You can capture the value of the filter to let TS know the value won't be reassigned.

if(filter) {
    const filterCapture = filter;
    const getFullWordfromQuery = translatedStatesName.filter((a) => a.toLowerCase().includes(filterCapture.toLowerCase()));
}

Playground link

See similar issue: Type guard inference of object's properties is lost in nested scopes #30576

Upvotes: 1

Related Questions