I'm new to using typescript. I want to know how to send multiple parameters in a typescript sense. For an example in JS we would:
const createOrUpdate = async (data = {name, email, password}) =>{
const params = {
TableName: Table,
Item: data
}
try{
await db.put(params).promise()
return { success: true }
} catch(error){
return { success: false}
}
}
I'm not sure how data = {name, email, password}
can be done in typescript. Appreciate it if someone can guide me through.
TS is JS with type annotations. Your JS idioms should work in TS. Consider this function (without async):
const user = "defaultName";
const email = "defaultEmail";
const password = "defaultPassword";
const createOrUpdate = (data = {user, email, password}) =>{
console.log(data);
}
createOrUpdate();
createOrUpdate({user: "u1", email: "e1", password: "p1"});
data
user
, email
, password
with values taken from variables with this names.This code is perfectly valid in TS.
On top of that, TS compiler is able to infer the type of the function, by looking at the default argument provided:
const createOrUpdate: (data?: {
user: string;
email: string;
password: string;
}) => void
You may also prefer to give the param an explicit type:
interface UserParams {
user: string;
email: string;
password: string;
}
const createOrUpdate2 = (data:UserParams = {user, email, password}) =>{
console.log(data);
}
createOrUpdate2();
createOrUpdate2({user: "u1", email: "e1", password: "p1"});
NOTE: I also changed name
to user
. While it is fine as a local variable, name
is a global variable from libdom. See Why does my variable show it's deprecated?