“This is the third day of my participation in the Gwen Challenge in November. Check out the details: [Last Gwen Challenge 2021]
preface
The focus is on global and local partitioning, which is the first step to getting started with Typescript
- Global type
- The global variable
- Partial type
Global type
The project root directory has tsconfig.json to configure TypeScript. The include attribute contains the files that need to validate TS
By default, types in xx.d.ts type files are registered as global. Here is an example
// index.d.ts
type T1 = number;
interface T2 {
a: string
};
declare namescpace golbal {
type T3 = '1' | '2'
}
Copy the code
<script lang="ts"> const t1: t1 = 1; const t2: T2 = { a: '' } const t3: golbal.T3 = '2' </script>Copy the code
Data types commonly used for definition (interfaces, environment variables, and so on)
The global variable
Global variables are also declared in xx.d.ts files
// index.d.ts
declare const HaHa = number;
declare namespace golbal {
const HaHa: string;
}
Copy the code
Global variable usage scenarios are primarily used in multiple places, such as imported third-party libraries
Vue.js dependencies are getting better in vue.js 3 and typescript support. If not supported, it may be replaced by a new dependency of the same functionality, so global variables are mostly for our own use
Partial type
<script lang="ts">
type T1 = string
const t1: T1 = '123'
<script>
Copy the code
A local type can be understood as a single place that needs to be used, written close to where it is used
summary
-
The benefits of using TypeScript in a project are self-evident, and the proper scoping of types and variables is part of the project planning.
-
When both global and local types exist, the local type is taken, even if it is an interface. Namespaces are a good way to avoid this situation
-
An idea for interface types: to unify the detail, list, and edit data types returned by the server, we can define only one type for three purposes
-
The concepts of global and local can be understood in conjunction with components. There are global components and local components.