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"});
- it takes one parameter:
data
- if no parameter is used, it takes a default value - an object consisting of 3 fields:
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"});
Playground
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?