In the last video we learned how to use interfaces, and in this video we’re going to learn about some other properties.

1. Optional properties

Let’s look at a piece of code like this

interface Person {
  name: string;
  age: number;
}

let tom: Person = {
  name: 'Tom'
};
Copy the code

In this code, we define a Person interface, and then we define an object Tom, and use Person to check this object. The result is an error, because we define the object Tom does not have the age property. When we want to make age a non-essential property we can put one after age, okay? In which case age becomes optional.

interface Person { name: string; age? : number; } let tom: Person = { name: 'Tom' };Copy the code

This object will not report an error if it writes or does not write age.

2. Arbitrary attributes

Sometimes we want to define an interface that allows you to have arbitrary properties, so we can write it like this

interface Person {
  [propName: string]: any;
}

let tom: Person = {
  name: 'Tom',
  age: 12,
  abc: {}
};
Copy the code

In the code above we defined the key of this object to be of type string, and the value of this object to be of type any. As you can see, we defined strings, numbers, and objects without error. This is how we can use any property.

3. Read-only properties

Sometimes we want values that can only be read and cannot be changed, so we can use readOnly in front of the key of the object

interface Person { readonly name: string; } let tom: Person = { name: 'Tom' }; Console. log(tom.name) //Tom can read Tom. name = "XXX" // Error cannot be changedCopy the code