I want to make function that receive value and run type guard function.
const checkType = (string: string) : string is 'a' => string === 'a'
/// const checkType: (string: string) => string is "a"
const getType = (value: 'a' | 'b') => checkType(value);
/// const getType: (value: 'a' | 'b') => boolean
I expected return type of getType
to be string is 'a'
but it is predicated as boolean
.
Can the {value} is {Type}
return guard work on in one function?
Can't it be conveyed to another function?
CodePudding user response:
The return type string is 'a'
just conveys typescript that it is a type guard. It will anyway return a boolean
, since type guards are used to confirm types in runtime.
Can't it be conveyed to another function?
Yes, you can add the guard function in an if
statement as given below. This will make sure if the guard check passes in runtime, it practically confirms that it's of the given type.
const isLiteralA = (string: string) : string is 'a' => string === 'a'
function myFunction(stringValue: string) {
if (isLiteralA(stringValue)) {
// Any operation on `stringValue` inside this if statement will assume it to be
// the string literal "a" since stringValue passed the guard check for the same
}
else {
// If `stringValue` does not pass the guard check, do something else (if required)
}
}
You may refer to: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates