This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
Examples of TypeScript
This article explores the interface interface.Copy the code
Interface interface
Interface to use
Interface is used to define common types. We agree to use uppercase letters to distinguish interfaces.
/ / 1
// Define an interface User
interface User {
name: string
age: number
}
// Define a variable
const bear: User = {
name: 'bear'.age: 20
}
Copy the code
Above we use the interface syntax to define an interface User. The interface constrains the variable bear to have two attributes, name and age. Attribute missing or overflow is not allowed.
/ / 2
// Also define an interface User
interface User {
name: string
age: number
}
// define function one
const getUserName = (user: User): string= > {
return user.name
}
// define function 2
const setUserName = (user: User, name: string): void= > {
user.name = name
}
Copy the code
We also define an interface User and two functions, getUserName and setUserName.
// Call the function getUserName.
const user = {name: 'bear'.age: 10}
getUserName(user) // bear
// Call the function getUserName.
getUserName({name: 'bear'.age: 10}) // Error message
Copy the code
Notice that we pass parameters to the function in different ways and get two different results. Method one is passed in as a cache variable with no error and gets the correct result. Method two, passed in as a literal, prompts an error. The reason is that TypeScript does strong validation when passing objects directly as literals.
Interface modifier
Optional modifiers (?)
/ / 3
interface User {
name: string, age? : number }Copy the code
If we want one or more attributes to be optional, we can use? Modifier representation.
Readonly modifiers
/ / 4
interface User {
readonly name: string,
age: number
}
Copy the code
If you want one or more attributes to be readable only, you can use the readonly modifier.
Iii. Arbitrary Attributes ([])
/ / case 5
interface User {
name: string,
age: number,
[propName: string]: any
}
Copy the code
If we allow the inclusion of additional attributes, we can use the method in Example 5 above.
Interface inheritance
/ / case 6
interface User {
name: string
}
interface student extends User{
study(): string
}
Copy the code
Interface inheritance is implemented through the extends syntax. The student interface in Example 6 above constrains that it must include the name attribute, as well as its own study method.
Interface and Type
The difference between an interface and a type alias is that an interface can only represent an object, not the underlying type. By default, we use interface definitions when we can use them, and use type aliases when we can’t.
Finish this! If this article helps you at all, please give it a thumbs up.