Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
const name = first + ' ' + last;
console.log(name);
}
sayName({ first: 'Bob' });
The trick is to first put in brackets what keys you want to pick from the argument object, with key=value for any defaults. Follow that with the : and a type declaration.
This is a little different than what you were trying to do, because instead of having an intact params object, you have instead have dereferenced variables.
If you want to make it optional to pass anything to the function, add a ? for all keys in the type, and add a default of ={} after the type declaration:
function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
var name = first + " " + last;
alert(name);
}
sayName();
Answer from jpadvo on Stack OverflowActually, there appears to now be a simple way. The following code works in TypeScript 1.5:
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
const name = first + ' ' + last;
console.log(name);
}
sayName({ first: 'Bob' });
The trick is to first put in brackets what keys you want to pick from the argument object, with key=value for any defaults. Follow that with the : and a type declaration.
This is a little different than what you were trying to do, because instead of having an intact params object, you have instead have dereferenced variables.
If you want to make it optional to pass anything to the function, add a ? for all keys in the type, and add a default of ={} after the type declaration:
function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
var name = first + " " + last;
alert(name);
}
sayName();
Typescript supports default parameters now:
https://www.typescriptlang.org/docs/handbook/functions.html
Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:
function sayName(firstName: string, lastName = "Smith") {
const name = firstName + ' ' + lastName;
alert(name);
}
sayName('Bob');
Videos
type OrderInfo = {
quantity: number;
productID: number;
price: number;
onSale: boolean
}
function order(orderInfo: OrderInfo): void { // I want onSale to default to true
}
order({quantity: 5, productID: 11, price: 5})I want onSale to default to true in the order function so I don't have to mention it when calling it.
https://www.typescriptlang.org/play/?#code/C4TwDgpgBA8gTgEwnAkgOwGYHsoF4oDeAUFKVAI4CuAhmsAJagBcUalAtgEbIDcJZYOFgSUAxsBQARFmy69+pQfVEQZHbnD5koWNAGVqAG1VROWLMdpEAvkSIZKacfV07EyABRZ3qTFhbwSL7YAJQsAG5Y9AiEdrZE3kEeBFS0DMxQAKwANFCCwmIS0lAAjCW5SiosmdYhUAD09VAoUADuaTr6RtDAOEgY1JSGwFC9o3CUEHZAA