-
Notifications
You must be signed in to change notification settings - Fork 12
Literal Reduction
When expanding a macro's body, the ts-macros transformer knows which values are literals (strings, numbers, arrays, objects, etc.), and so it can reduce the expanded code in some ways.
In the example below, we know that numA is 5 and numB is 10, so instead of expanding the code to 5 + 10, we directly expand it to the produced value, which is 15.
function $add(numA: number, numB: number) : number {
return numA + numB;
}$add!(5, 10);15If the condition of an if statement / ternary expression is a literal, then the entire condition will be removed and only the resulting code will be expanded.
function $log(multiply: boolean, number: number) {
console.log(multiply ? number * 2 : number);
}
// If version
function $log(multiply: boolean, number: number) {
if (multiply) console.log(number * 2);
else console.log(number);
}$log!(false, 10);
$log!(true, 15);console.log(10);
console.log(30);Object access expressions get replaced with the value if the accessed object is a literal. You can prevent this by wrapping the object / array in paranthesis.
function $add(param1: {
user: { name: string }
}, arr: [number, string]) {
return param1.user.name + arr[0] + arr[1];
}$add!({
user: { name: "Google" }
}, [22, "Feud"]);"Google22Feud";You can concat array literals with the spread syntax, like you do in regular javascript:
function $concatArrayLiterals(a: Array<number>, b: Array<number>) : Array<number> {
return [...a, ...b];
}$concatArrayLiterals!([1, 2, 3], [4, 5, 6]);[1, 2, 3, 4, 5, 6];