Typescript default value in object

TypeScript Default Parameters

Summary: in this tutorial, you will learn about TypeScript default parameters.

Introduction to TypeScript default parameters

JavaScript supported default parameters since ES2015 (or ES6) with the following syntax:

function name(parameter1=defaultValue1. ) < // do something >Code language: JavaScript (javascript)

In this syntax, if you don’t pass arguments or pass the undefined into the function when calling it, the function will take the default initialized values for the omitted parameters. For example:

function applyDiscount(price, discount = 0.05) < return price * (1 - discount); > console.log(applyDiscount(100)); // 95Code language: JavaScript (javascript)

In this example, the applyDiscount() function has the discount parameter as a default parameter.

When you don’t pass the discount argument into the applyDiscount() function, the function uses a default value which is 0.05 .

Similar to JavaScript, you can use default parameters in TypeScript with the same syntax:

function name(parameter1:type=defaultvalue1, parameter2:type=defaultvalue2. ) < // >Code language: JavaScript (javascript)

The following example uses default parameters for the applyDiscount() function:

function applyDiscount(price: number, discount: number = 0.05): number < return price * (1 - discount); > console.log(applyDiscount(100)); // 95Code language: JavaScript (javascript)

Notice that you cannot include default parameters in function type definitions. The following code will result in an error:

let promotion: (price: number, discount: number = 0.05) => number;Code language: JavaScript (javascript)
error TS2371: A parameter initializer is only allowed in a function or constructor implementation.Code language: JavaScript (javascript)

Default parameters and Optional parameters

Like optional parameters, default parameters are also optional. It means that you can omit the default parameters when calling the function.

In addition, both the default parameters and trailing default parameters share the same type. For example, the following function:

function applyDiscount(price: number, discount: number = 0.05): number < // . >Code language: JavaScript (javascript)
function applyDiscount(price: number, discount?: number): number < // . >Code language: JavaScript (javascript)
(price: number, discount?: number) => numberCode language: PHP (php)

Optional parameters must come after the required parameters. However, default parameters don’t need to appear after the required parameters.

When a default parameter appears before a required parameter, you need to explicitly pass undefined to get the default initialized value.

The following function returns the number of days in a specified month and year:

function getDay(year: number = new Date().getFullYear( ), month: number): number < let day = 0; switch (month) < case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 4: case 6: case 9: case 11: day = 30; break; case 2: // leap year if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) day = 29; else day = 28; break; default: throw Error('Invalid month'); > return day; >Code language: JavaScript (javascript)

In this example, the default value of the year is the current year if you don’t pass an argument or pass the undefined value.

Читайте также:  Resource php тип данных

The following example uses the getDay() function to get the number of days in Feb 2019:

let day = getDay(2019, 2); console.log(day); // 28Code language: JavaScript (javascript)

To get the number of days in Feb of the current year, you need to pass undefined to the year parameter like this:

let day = getDay(undefined, 2); console.log(day);Code language: JavaScript (javascript)

Summary

  • Use default parameter syntax parameter:=defaultValue if you want to set the default initialized value for the parameter.
  • Default parameters are optional.
  • To use the default initialized value of a parameter, you omit the argument when calling the function or pass the undefined into the function.

Источник

Default Value for Object Parameters in TypeScript

Default Value for Object Parameters in TypeScript

  1. Default Values for Objects in TypeScript
  2. Pass Default Values Through Destructuring in TypeScript
  3. Make Certain Attributes of an Object Have Default Values in TypeScript
  4. Use the Partial Keyword to Make All Fields Have Default Values in TypeScript

Default parameters are something that a user wants to always incorporate into the code. TypeScript has a facility for providing default parameters in objects and passing objects in functions.

This tutorial will focus on how default parameters can be used in TypeScript.

Default Values for Objects in TypeScript

A function can be defined to work with default values if, in case, no value is passed to the function. The following code segment demonstrates how this can be achieved.

interface Config   file : string ;  test : boolean;  production : boolean;  dbUrl : string; > function getConfig ( config : Config = < file : 'test.log', test : true,  production : false, dbUrl : 'localhost:5432' >)   console.log(config); >  getConfig();  getConfig(: 'prod.log', test: false, production : true, dbUrl : 'example.com/db'>); 
  "file": "test.log",  "test": true,  "production": false,  "dbUrl": "localhost:5432" >    "file": "prod.log",  "test": false,  "production": true,  "dbUrl": "example.com/db" > 

The above shows how default values can be used in TypeScript.

The getConfig function uses the default values assigned in the function definition if no values for the Config object are passed while calling the function, which can be seen in the case of the first call to the getConfig function.

In the second call to the function, the default values are overridden by the values passed to the function.

Pass Default Values Through Destructuring in TypeScript

TypeScript also has the support for passing down default values to function by destructuring the attributes of an object. The following code segment shows how it can be achieved.

interface Person   firstName : string ;  lastName : string ; >  function getPerson( = 'Steve', lastName = 'Jobs' > : Person )   console.log( firstName + ' ' + lastName); >  getPerson(<> as Person);  getPerson(< firstName : 'Tim', lastName : 'Cook'>); 

Thus like the previous examples, there are two calls to the function getPerson , one using the default values while the other using the values passed on the function. The difference is for the default case, an empty object <> is to be passed, or TypeScript will throw an error — Expected 1 arguments, but got 0 .

Make Certain Attributes of an Object Have Default Values in TypeScript

We can make certain attributes of an object have default values while the others are required while assigning attributes to the object or passing the object to a function. This can be done by using the ? operator.

The following code segment shows how it can be done.

interface Config   file? : string ;  test? : boolean;  production : boolean;  dbUrl : string; >  function getConfig( < file = 'api.log', test = true, production, dbUrl> : Config )   var config : Config =   file,  test,  production,  dbUrl  >;  console.log(config); >  getConfig(true, dbUrl : 'example.com/db'>); 
  "file": "api.log",  "test": true,  "production": true,  "dbUrl": "example.com/db" > 

Use the Partial Keyword to Make All Fields Have Default Values in TypeScript

The Partial keyword is a useful tool to make all the attributes of an object optional and can be used to make all the fields of an object have default values in the case of a function definition. Use the example from above.

interface Config   file : string ;  test : boolean;  production : boolean;  dbUrl : string; >  function getConfig( < file = 'api.log', test = true, production = false, dbUrl = 'localhost:5432'> : PartialConfig> )   var config : Config =   file,  test,  production,  dbUrl  >;  console.log(config); >  getConfig(true>); 
  "file": "api.log",  "test": true,  "production": true,  "dbUrl": "localhost:5432" > 

Thus in the example above, we can see all the fields have default values, and the value for the production attribute has been overridden.

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

Related Article — TypeScript Object

Источник

How To Set A Default Parameter In TypeScript?

Tim Mouskhelichvili

Sometimes developers need to define a default parameter for a TypeScript function. Luckily, TypeScript, just like its counterpart JavaScript, offers a simple way to define default parameters.

In TypeScript, you can define a default parameter like so:

typescriptconst getUser = (firstName: string, role = 'user'): string => < return `$ | $ `; >

This article will go through everything about default parameters in TypeScript and answer the most common questions.

The definition

JavaScript supports default parameters since the ES2015 version.

TypeScript also fully supports default parameters.

Default parameters are optional parameters that fall back to a default value if it has no value or is undefined .

The difference between calling a function and omitting an optional parameter vs a default parameter is:

  • If an optional parameter has no value, the parameter’s value is undefined .
  • If a default parameter has no value, the parameter’s value is the default value.

Default parameters are set using the assignment operator (=).

Here is an example of a function with a default parameter:

typescriptconst outputUser = (firstName: string, lastName = 'Mousk'): void => < console.log(`$ $ `); > // Outputs: 'Tim Mousk' outputUser('Tim'); // Outputs: 'Bob Clark' outputUser('Bob', 'Clark');

In this example, the lastName parameter is an optional parameter with a default value.

When we call the outputUser function, we only need to pass an argument for the first parameter.

If the lastName parameter has no value or is undefined , it will fall back to its default value.

Note: Here we are using string interpolation to concat the strings.

Default parameters rules

Here are a few default parameters rules in TypeScript:

  • In TypeScript, the type of a default parameter is inferred. You don’t have to specify its type explicitly.
  • Default parameters need to come AFTER the required parameters. They need to come last.
  • Default parameters are optional.
  • A default parameter takes the default value if you omit the argument or pass undefined to it.
  • A developer can set multiple default parameters inside a function.

The best Web Development course in 2023! 👉 Learn Web Development

How to pass a function as the default value?

You can pass a function result as the default value to a default parameter.

Here is an example of how to do it:

typescriptconst outputUser = (name: string, year = new Date().getFullYear()): void => < console.log(`$ $ `); > // Outputs: 'Tim 2022' outputUser('Tim');

In this example, the year parameter is an optional parameter that fallbacks to the current year if it has no value.

How to pass default values through destructuring?

TypeScript also supports default values when destructuring an object inside a function definition.

Here is an example of how to do it:

typescriptinterface IUser < name: string; year?: number; > const outputUser = (< name, year = new Date().getFullYear() >: IUser): void => < console.log(`$ $ `); > // Outputs: 'Tim 2022' outputUser(< name: 'Tim' >);

In this example, we first destruct the user object.

Then, we define a default value for the year property.

Final thoughts

As you can see, setting a default parameter in TypeScript is easy.

To define one yourself, use the assignment operator and provide a default value to it.

Be sure always to place the default parameters AFTER the required ones.

typescript default parameter

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Оцените статью