- ts-node 默认不读tsconfig
- private property in interface
- Cannot redeclare block-scoped variabl
- 类型定义库 definitelytyped
- A namespace-style import cannot be called or constructed, and will cause a failure at runtime
- worth to learn typescript project
- interface 允许 semicolon,comma
- 数组结构
- Type ‘Timeout’ is not assignable to type ‘number’.ts(2322)
ts-node 默认不读tsconfig
在已有的模块的属性上 使用 declare 扩展类型,比如在 express 的 Request 上扩展 $uid,这样做
types.d.ts
/// <reference types="express" />/*** This type definition augments existing definition*/declare namespace Express {export interface Request {$uid?: any; // current user id$token?: any; // current token}}
这时即可扩展 req 的类型,但是如果是使用 ts-node 启动项目,仍然会报错
/danke-chat-server/node_modules/ts-node/src/index.ts:293
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/chat-server.ts:67:11 - error TS2339: Property '$token' does not exist on type 'Request<ParamsDictionary>'.
这是因为 ts-node in 7.0.0, default do not Load files from tsconfig.json on startup, you should specific —files.
private property in interface
在 interface 中定义一个 implements 的 class 的 private 或 protected 属性,是没有意义的
interface IModule {
name: string;
}
class ModuleA implements IModule {
private name;
constructor() {
this.name = 'king';
}
}
// 以上是没有意义的
但是可以通过 readonly 实现
interface IModule {
readonly name: string;
}
class ModuleA implements IModule {
public readonly name: string;
constructor() {
this.name = 'king';
}
}
Cannot redeclare block-scoped variabl
// add tsconfig.json , write this can fix
{
"compilerOptions": {
"lib": [
"es2015"
]
}
}
类型定义库 definitelytyped
@types/express npm 类型定义库 http://definitelytyped.org/
package 搜索 https://microsoft.github.io/TypeSearch/
A namespace-style import cannot be called or constructed, and will cause a failure at runtime
TypeScript 2.7 引入了 esModuleInterop 编译选项用以区分命名空间导入和默认导入的行为,使得模块的导入行为更符合 ES6 模块的规范,同时与 Babel 的转译行为保持一致:
例如:
命名空间的导入方式:
import * as foo from 'foo';`
默认导入的导入方式:
import b from 'bar';
开启 esModuleInterop 编译选项后,当使用命名空间的导入方式时,导入对象不可调用/不可实例化。当使用默认导入的导入方式时,导入对象应当可调用/可实例化。
例如:
开启 esModuleInterop 前
import * as express from 'express';
express();
开始 esModuleInterop 后,导入应改为
import express from 'express';
express();
worth to learn typescript project
https://codebrains.io/setting-up-express-with-typescript/
http://withjavascript.com/blog/tdd-a-restful-api-with-node-express-typescript-and-jest-part-1
interface 允许 semicolon,comma
interface user {
id: string,
name: string,
email: string,
}
interface user {
id: string;
name: string;
email: string;
}
数组结构
let [err, response]: [MongoError, any] = mongo.action
Type ‘Timeout’ is not assignable to type ‘number’.ts(2322)

// 使用 windows
let timerId = window.setTimeout(() => {})
