Issue
Consider the following MWE:
function print (x: number) {
console.log(x)
}
function noString (a: number | string) {
if (typeof a === 'string') {
throw new Error('error')
}
}
export function funOne () {
const a: number | string = 'abc'
if (typeof a === 'string') {
throw new Error('error')
}
print(a)
}
export function funTwo () {
const a: number | string = 'abc'
noString(a)
print(a)
}
I think funOne and funTwo are essentially the same. However, I got [tsserver 2345] [E] Argument of type 'string' is not assignable to parameter of type 'number'. on the last line in funTwo.
Why does this happen and how should I avoid this?
Solution
This happens because typescript doesn't know that noString is used as a type check. But you can tell typescript about it, for example like this:
function noString(a: number | string): number {
if (typeof a === 'string') {
throw new Error('error');
}
return a;
}
export function funTwo() {
const a: number | string = 'abc';
print(noString(a));
}
Or you could use a type predicate:
function noString(a: string | number): a is number {
if (typeof a === 'string') {
throw new Error('error');
}
return true;
}
export function funTwo() {
const a: number | string = 'abc';
if (noString(a)) {
print(a);
}
}
As mentioned in the comments by @Artyer and @futur, you could also use asserts:
function noString(a: string | number): asserts a is number {
if (typeof a === 'string') {
throw new Error('error');
}
}
export function funTwo() {
const a: number | string = 'abc';
noString(a)
print(a);
}
Answered By - Kirill Simonov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.