TypeScript 项目
编译上下文
tsconfig.json: 配置一些编译信息
编译选项
可以通过 compilerOptions 来定制你的编译选项,对一些ts规则进行设置。
{
"compilerOptions": {
"noUnusedLocals": true, // 有未使用的变量时,抛出错误
"noUnusedParameters": true, // 有未使用的参数时,抛出错误
"paths": { //路径配置
"@/*": ["./src/*"],
"@@/*": ["./src/.umi/*"]
}
}
}
声明空间
类型声明空间
类型声明空间与变量声明空间;
class Foo {}
interface Bar {}
type Bas = {};
都可作类型使用,但 interface Bar,不能做变量使用。
同理,var等一些变量,也只能在变量声明空间使用,不能用作类型注解。
模块
全局模块和文件模块。
全局模块下面的全局变量是非常危险的,不要使用,使用文件模块。
文件模块
导入导出
多个导出
export const Page = [1, 2, 3];
export type someType = {foo: string};
const arr = [2,3];
export const data = arr;
export {data, someType};
import {data, someType} from '@/'
重命名
const someVar = 123;
export { someVar as aDifferentName };
import { someVar as aDifferentName } from './foo';
导入导出
import * as foo from './foo'; //导出全部
export * from './foo'; //从其他模块导入后整体导出
export { someVar } from './foo'; //从其他模块导入后,部分导出
export { someVar as aDifferentName } from './foo'; // 部份导入导出重命名
默认
const Page = ()=>{};
export default Page; //默认导出
import Page from ''; //导入
模块路径
模块路径
当你使用 import * as foo from ‘foo’,将会按如下顺序查找模块:
- ./node_modules/foo
- …/node_modules/foo
- …/…/node_modules/foo
- 直到系统的根目录
全局模块
declare module 'foo' {
// some variable declarations
export var bar: number;
}
import * as foo from 'foo';
// TypeScript 将假设(在没有做其他查找的情况下)
// foo 是 { bar: number }
declare namespace TYPES{
type TUser = {name: string};
type T...
}
//全局的命名空间,可以直接使用 TYPES.TUser
命名空间
namespace
确保创建的变量不会泄漏至全局命名空间