TS is essentially JS with added type annotations. Your JS coding style should seamlessly transition to TS.
Take a look at this function (excluding async functionality):
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 accepts a single parameter:
data
- if no parameter is provided, it defaults to an object with 3 fields:
user
, email
, password
with values from variables of the same names.
This code is completely valid in TypeScript.
Furthermore, the TS compiler can automatically infer the function's type by analyzing the default argument:
const createOrUpdate: (data?: {
user: string;
email: string;
password: string;
}) => void
You could also explicitly define the parameter's 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 have replaced name
with user
. While it is fine for local use, name
is a global variable in libdom. See Why does my variable show it is deprecated?