i noticed , function (using default params) doesn't cause error on compilation.
function buildaddress(address1 = 'n/a', address2: string) { displayaddress( address1 +' '+ address2); }
but function (using optional params) does.
function buildaddress(address1?: string, address2: string) { displayaddress( address1 +' '+ address2); }
why ?
i'm surprised of behavior, normal ? have benefit ? feature or bug ?
have tried use first version without passing first argument?
function buildaddress(address1: string = 'n/a', address2: string) { console.log(address1, address2); } buildaddress("address2");
results in:
supplied parameters not match signature of call target
if put default value 2nd parameter though:
function buildaddress(address1: string , address2: string = 'n/a') { console.log(address1, address2); }
it works.
adding default value first parameter helps in case pass undefined
:
buildaddress(undefined, "address2");
as compiles to:
function buildaddress(address1, address2) { if (address1 === void 0) { address1 = 'n/a'; } console.log(address1, address2); }
so in reality if you're doing first parameter isn't optional @ all, must pass value, , default value if pass undefined
.
compiler won't complain function signature because first parameter has value sure, in 2nd function, since first param optional compiler complains.
edit
this behvior can used safe guard against undefined
values, example:
function buildaddress(address1 = 'n/a', address2: string) { displayaddress(address1 + ' ' + address2); } function getaddress1(): string { // logic here, might return undefined } buildaddress(getaddress1(), "address 2");
i'm not sure if design or byproduct, it's useful in cases.
Comments
Post a Comment