Typescript default value in type

TypeScript How to set a default value with Interface

Interface is a powerful feature supported by many programming languages. However, if we want to set a default value, we need to set it one property by one property.

Is there any good alternative instead of assigning a value one by one?

Repeating the change if setting a default value one by one

Normal way to set a default value to a property is the following.

interface MyInterface < a: number; b: string; c: unknown; >const data1: MyInterface = < a: 0, b: "default-string", c: "something", >; const data2: MyInterface = < a: 0, b: "default-string", c: < value: 1 >, >;

Property a and b are the default value. Only property c is the difference. If we need to change the default value, we have to change two places. If we have many objects to be updated, we might forget to update one of them.
Likewise, when we add additional properties, we need to add them to multiple places.

Читайте также:  Эффект перекатывания

This is what we need to improve.

Prepare an object that has default value set

Using Spread Operator

If we can copy the default value to the target object, it’s easy to reuse it by using a spread operator.

const MyInterfaceDefault: MyInterface = < a: 0, b: "default-string", c: null, >; const data1: MyInterface = < . MyInterfaceDefault, c: "something", >; const data2: MyInterface = < . MyInterfaceDefault, c: < value: 1 >, >; console.log(data1); // < a: 0, b: 'default-string', c: 'something' >console.log(data2); // < a: 0, b: 'default-string', c: < value: 1 >>

Please check the following article if you still don’t know about the three dots called spread operator.

The spread operator (three dots) is used to copy an array and expand an array to pass the values to another object or function parameters. It can also be used as rest parameters in a function to indicate that the function can take as many arguments as you want. The spread operator is handled as a shallow copy. Therefore you need to be careful if you use it for an object that has objects in the property list.

As you can see, both objects have the same value for properties a and b.

Prepare a function that set the default value

You might even think that it is cumbersome to use a spread operator for each object creation. If you think so, preparing a function is an alternative.

function createMyInterface(options?: Partial): MyInterface < const defaultValue: MyInterface = < a: 0, b: "default-string", c: null, >; return < . defaultValue, . options, >> console.log(createMyInterface()); // < a: 0, b: 'default-string', c: null >console.log(createMyInterface(< a: 999, c: "set-my-string" >)); //

You don’t have to use the spread operator for each object creation. It is easier to create an object.

Default value with a class definition that implements an interface

What if we use an interface for a class definition?

class MyClass implements MyInterface < public a: number = 22; public b: string = "I'm good"; public c: unknown = < value: 55 >; >

Do we always need to set it like this?

For a class definition, we can instead extend a class. Let’s define a base class then.

class MyInterfaceBase implements MyInterface < public a: number = 22; public b: string = "I'm good"; public c: unknown = < value: 55 >; > const instance = new MyInterfaceBase(); console.log(instance.a); // 22 console.log(instance.b); // I'm good console.log(instance.c); //

Once we create the base class, we can extend it for our desired class.

class ExtendedMyClass extends MyInterfaceBase < >const instance = new ExtendedMyClass(); console.log(instance); // ExtendedMyClass < a: 22, b: "I'm good", c: < value: 55 >>

If the class doesn’t have to have additional properties, define the class with extends keyword without having anything in the class.

If you need additional properties, you can of course write in the following way.

class ExtendedMyClass2 extends MyInterfaceBase < public d: number = 1234567890; >const instance2 = new ExtendedMyClass2(); console.log(instance2); // ExtendedMyClass2 < // a: 22, // b: "I'm good", // c: < value: 55 >, // d: 1234567890 // >

We often need to build similar structures in different objects. Some functions require the same variables but want to ha.

Источник

Typescript default value in type

Last updated: Jan 20, 2023
Reading time · 4 min

banner

# Setting TypeScript interface default values using spread syntax (. )

To set default values for an interface:

  1. Use the Pick utility type to only select the properties that have default values.
  2. Use the spread syntax to unpack the rest of the properties after the defaults when creating an object.
Copied!
interface Person name: string; age: number; country: string; > const defaults: PickPerson, 'name' | 'country'> = name: '', country: '', >; const person1: Person = . defaults, name: 'Bobby Hadz', age: 30, >; // 👇️ console.log(person1);

We used the Pick utility type to get the type of the name and country properties from the Person interface and specified default values for the 2 properties.

Copied!
interface Person name: string; age: number; country: string; > // type Example = // name: person1; // country: person1; // > type Example = PickPerson, 'name' | 'country'>;

You can pick multiple property names by separating them with a pipe | .

If you only need to specify a default value for 1 property, you don’t have to use a pipe.

Copied!
interface Person name: string; age: number; country: string; > const defaults: PickPerson, 'name'> = name: '', >; const person1: Person = . defaults, name: 'Bobby Hadz', age: 30, country: 'Chile', >; // 👇️ console.log(person1);

The next step is to set a new variable to the Person type and override the defaults using the spread syntax (. ).

# Setting TypeScript interface default values with a custom function

Alternatively, you can use a custom function.

  1. Create an initializer function that defines the default values for the type
  2. Use the spread syntax (. ) to override the defaults with user-provided values.
Copied!
interface Person name: string; age: number; country: string; > function initPerson(options?: PartialPerson>): Person const defaults = name: '', age: 0, country: '', >; return . defaults, . options, >; > const p1: Person = initPerson(); console.log(p1); // 👉️ const p2: Person = initPerson( name: 'Tom', age: 30 >); console.log(p2); // 👉️

We created an initPerson function that can be called with an options object or no parameters at all.

The function defines the default values for the Person interface and uses the spread syntax (. ) to unpack the defaults before unpacking any of the user-provided values.

We used the Partial utility type to set all of the properties in the Person interface to optional in the function’s parameter.

Any of the values you pass to the function will override the default values.

Copied!
const obj1 = name: 'Bobby Hadz', >; const obj2 = name: 'Alfred', >; const obj3 = . obj1, . obj2, >; console.log(obj3); // 👉️

When unpacking multiple objects with the same key, the object that gets unpacked the last overrides the previous values.

When using this approach, we can be sure that the object, the initPerson function creates will always conform to the Person interface, even if it gets called with no parameters.

It should be noted that you can’t explicitly set default values in an interface, because interfaces and types get removed during compilation.

They don’t exist at runtime, so we can only leverage them during the development process.

# Setting undefined as the default value for interface properties

If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional.

Copied!
interface Person name?: string; age?: number; country: string; > const p1: Person = country: 'Germany', >; // 👇️ The rest are optional p1.age = 30; p1.name = 'Bobby Hadz';

We used a question mark to mark the name and age properties as optional.

Now we aren’t required to set them when creating an object that uses the Person interface.

You can set the properties on the object using dot or bracket notation at a later stage.

Even though TypeScript doesn’t require us to set the name and age properties when creating the object, it still checks that all properties added later on conform to the Person interface.

Copied!
interface Person name?: string; age?: number; country: string; > const p1: Person = country: 'Germany', >; // ⛔️ Error: Property 'test' does not exist on type 'Person' p1.test = 'hello'; // ⛔️ Error: Type '5' is not assignable to type 'string' or 'undefined' p1.name = 5;

We are only able to add properties that are defined on the interface and match the specified type.

If you need to create an object based on an interface, click on the following link.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Typescript default value in type

Last updated: Jan 20, 2023
Reading time · 4 min

banner

# Setting TypeScript interface default values using spread syntax (. )

To set default values for an interface:

  1. Use the Pick utility type to only select the properties that have default values.
  2. Use the spread syntax to unpack the rest of the properties after the defaults when creating an object.
Copied!
interface Person name: string; age: number; country: string; > const defaults: PickPerson, 'name' | 'country'> = name: '', country: '', >; const person1: Person = . defaults, name: 'Bobby Hadz', age: 30, >; // 👇️ console.log(person1);

We used the Pick utility type to get the type of the name and country properties from the Person interface and specified default values for the 2 properties.

Copied!
interface Person name: string; age: number; country: string; > // type Example = // name: person1; // country: person1; // > type Example = PickPerson, 'name' | 'country'>;

You can pick multiple property names by separating them with a pipe | .

If you only need to specify a default value for 1 property, you don’t have to use a pipe.

Copied!
interface Person name: string; age: number; country: string; > const defaults: PickPerson, 'name'> = name: '', >; const person1: Person = . defaults, name: 'Bobby Hadz', age: 30, country: 'Chile', >; // 👇️ console.log(person1);

The next step is to set a new variable to the Person type and override the defaults using the spread syntax (. ).

# Setting TypeScript interface default values with a custom function

Alternatively, you can use a custom function.

  1. Create an initializer function that defines the default values for the type
  2. Use the spread syntax (. ) to override the defaults with user-provided values.
Copied!
interface Person name: string; age: number; country: string; > function initPerson(options?: PartialPerson>): Person const defaults = name: '', age: 0, country: '', >; return . defaults, . options, >; > const p1: Person = initPerson(); console.log(p1); // 👉️ const p2: Person = initPerson( name: 'Tom', age: 30 >); console.log(p2); // 👉️

We created an initPerson function that can be called with an options object or no parameters at all.

The function defines the default values for the Person interface and uses the spread syntax (. ) to unpack the defaults before unpacking any of the user-provided values.

We used the Partial utility type to set all of the properties in the Person interface to optional in the function’s parameter.

Any of the values you pass to the function will override the default values.

Copied!
const obj1 = name: 'Bobby Hadz', >; const obj2 = name: 'Alfred', >; const obj3 = . obj1, . obj2, >; console.log(obj3); // 👉️

When unpacking multiple objects with the same key, the object that gets unpacked the last overrides the previous values.

When using this approach, we can be sure that the object, the initPerson function creates will always conform to the Person interface, even if it gets called with no parameters.

It should be noted that you can’t explicitly set default values in an interface, because interfaces and types get removed during compilation.

They don’t exist at runtime, so we can only leverage them during the development process.

# Setting undefined as the default value for interface properties

If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional.

Copied!
interface Person name?: string; age?: number; country: string; > const p1: Person = country: 'Germany', >; // 👇️ The rest are optional p1.age = 30; p1.name = 'Bobby Hadz';

We used a question mark to mark the name and age properties as optional.

Now we aren’t required to set them when creating an object that uses the Person interface.

You can set the properties on the object using dot or bracket notation at a later stage.

Even though TypeScript doesn’t require us to set the name and age properties when creating the object, it still checks that all properties added later on conform to the Person interface.

Copied!
interface Person name?: string; age?: number; country: string; > const p1: Person = country: 'Germany', >; // ⛔️ Error: Property 'test' does not exist on type 'Person' p1.test = 'hello'; // ⛔️ Error: Type '5' is not assignable to type 'string' or 'undefined' p1.name = 5;

We are only able to add properties that are defined on the interface and match the specified type.

If you need to create an object based on an interface, click on the following link.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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