CDEC - Jay
弱类型 VS. 强类型
静态类型检查 VS. 动态类型检查
个人理解: 静态类型检查就是在编译期间就能检查到具体的类型;弱类型则是偏向于容忍隐式类型转换
更多讨论,请参考:知乎讨论
有没有可能,为 JavaScript 插上类型的翅膀?
那,如何使用 TypeScript 呢?
最便捷的演练 TypeScript 的地方莫过于:
TypeScript Playgroud
当然,这种方式更多用于学习语法。
npm i typescript -g
全局安装 TypeScript或者 npm i typescript -D
本地安装
tsc hello.ts
编译 ts 文件Deno:https://github.com/denoland/deno
A secure JavaScript/TypeScript runtime built with V8, Rust, and Tokio
Tokio:The asynchronous run-time for the Rust programming language.
import { listenAndServe } from '../deno_std/net/http.ts';
function uint8array2string(uint8Array: Uint8Array): string {
return new TextDecoder().decode(uint8Array);
}
function string2uint8array(text: string): Uint8Array {
return new TextEncoder().encode(text);
}
async function main() {
await listenAndServe('0.0.0.0:9999', req => {
console.log(req.url, req.method, req.headers, req.proto);
req.respond({
status: 200,
headers: new Headers({ ContentType: 'application/json' }),
body: string2uint8array(JSON.stringify({ hello: 'deno!' }))
});
});
}
main();
interface IPerson {
age?: number; // 可选属性
readonly name: string; // 只读属性
[idx: number]: string; // 索引类型(模拟字典)
}
class Person implements IPerson {
[idx: number]: string;
age?: number;
name: string;
}
interface IFunc {
(n1: number, n2: number): number;
}
const add: IFunc = function(n1, n2) {
// 有了类型约束后,会自动进行类型推断
return n1 + n2;
};
interface IFunc2 {
(n1: number, n2: number): number;
displayName: string;
}
const add2: IFunc2 = function(n1, n2) {
// 有了类型约束后,会自动进行类型推断
return n1 + n2;
};
add2.displayName = 'add2'; // 如果没有这句,会怎样?
interface PersonInterface {
name: string;
age?: number;
sleep: (hour: number) => string;
}
interface PersonCtor {
// 定义构造
new (name: string, age?: number): PersonInterface;
}
class PersonIns implements PersonInterface {
sleep: (hour: number) => string;
name: string;
}
function createPerson(ctor: PersonCtor, name: string): PersonInterface {
return new ctor(name);
}
createPerson(PersonIns, 'hi');
function fun1(a: { a: number }) {}
fun1({ a: 1, b: 2 });
Demo演示
Demo演示