There is a problem with type checking in TypeScript. There is an interface of the following form:

export interface ObjectRow { _id?: string; id: string; value: string | number; modificatedDate: number; } 

At some point, an object of type ObjectRow is received, and some actions need to be performed if a non-empty string has arrived at value. Written such a condition to check:

 if (typeof object.value === 'string' && object.value.length > 0) {...} 

However, an error occurs in this place: "Property 'length' does not exist on type 'number'" .

In theory, the first part of the condition does not pass, the second should be ignored - but for some reason this does not happen: TypeScript considers that if there is a possibility of the number coming, then the check for length is incorrect. I have already rewrote the condition several times - TypeScript still hacks it. Can you tell where to dig? In TypeScript, I'm still a beginner, I continue to google hard. I would be grateful for any recommendations.

    2 answers 2

    We look at the documentation on Union types. http://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types

    for your case we rule like this:

     const value = object.value; if (typeof value === 'string' && (<string>value).length > 0) { ...} 

    or

     if (typeof object.value === 'string' && (object.value as string).length > 0) { ... } 

    The second came up with for TSX.

    • Thank you very much, figured out! - kostyawh
    • The @overthesanity as operator is a type cast. And we have the same union. - Hooter
    • @kostyawh is enough to accept the answer. - Hooter
    • @Hooter, typescriptlang.org/play/… - overthesanity
    • @overthesanity, yes you are right, it is necessary like this: - Hooter

    Update your script script - everything works :

    screenshot

    In general, it was much better to check this:

     if (typeof x.value === 'string' && x.value)