Reputation:
I'm new to Typescript, just a question on type assertion.
Below is an example from my textbook:
function calculateTax(amount: number, format: boolean): string | number {
const calcAmount = amount * 1.2;
return format ? `$${calcAmount.toFixed(2)}` : calcAmount;
}
let taxNumber: string | number = calculateTax(100, false);
let taxString: string | number = calculateTax(100, true);
and the book which says:
No type conversion is performed by a type assertion, which only tells the compiler what type it should apply to a value for the purposes of type checking. SO they are equivalent to these statements
let taxNumber: number = calculateTax(100, false) as number;
let taxString: string = calculateTax(100, true) as string;
I'm confused, so calculateTax(100, false)
is string | number
,when we do the assertion by append as number to it, calculateTax(100, false) as number
becomes 'nu,ber' type, that's how taxNumber
can be consider as number as let taxNumber: number
, so why it is no type conversion involved?
Upvotes: 0
Views: 107
Reputation: 84922
so why it is no type conversion involved?
They're pointing out that when you run the code, whatever the javascript code returns is what it returns. Doing as number
doesn't change the behavior of the code, it's just a way of telling typescript "i know better than you, so don't check my types here".
If you truly do know better than typescript does, then type assertions are ok. But if you make a mistake (eg, if you say it's a number when it isn't), you'll have a bug in your code that typescript won't be able to tell you about.
By the way, you can do safer types on this function by using overloads:
function calculateTax(amount: number, format: true): string;
function calculateTax(amount: number, format: false): number;
function calculateTax(amount: number, format: boolean): string | number {
const calcAmount = amount * 1.2;
return format ? `$${calcAmount.toFixed(2)}` : calcAmount;
}
let taxNumber: number = calculateTax(100, false);
let taxString: string = calculateTax(100, true);
Upvotes: 2