0
interface Initializing {
  progress: number;
}

var isInitializing = (x: any): x is Initializing => {
  return typeof x.progress === 'number';
}

The above code can be compiled without any error.

My question is related to ":x is Initializing" clause in the code. It seems that it doesn't affect generated JavaScript.

What ": x is Initializing" clause is used for? What kind of type checking is done? It seems that it is generating the same code when I call the function 'isInitializing' with any parameter. It produce the same JS code.

Examples are much appreciated.

1 Answer 1

2

It's a user defined type guard. It doesn't generate any code, but when the function is used with an if statement the compiler will automatically consider the passed in object to be the type specified in the is clause within the if statement.

Here's an example:

interface Initializing {
  progress: number;
}

var isInitializing = (x: any): x is Initializing => {
  return typeof x.progress === 'number';
}

var obj = { progress: 1 };

// obj is type "{ progress: number; }" here    

if (isInitializing(obj)) {
    obj; // obj is type "Initializing" within this if statement
}

// obj is type "{ progress: number; }" here
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.