TypeScript
is a typed superset of JavaScript
that compiles to plain JavaScript.
dynamic types
,在运行时执行;TS 的是static types
,在开发阶段被设定。
// interface 的入参类型是个变量 ContentType
// 函数 save 接受的参数 a 的类型也指定为 ContentType
interface CacheHostGeneric<ContentType> {
save: (a: ContentType) => void;
}
// 入参类型分别为 Type 和 Cache,其中 Cache 继承自 CacheHostGeneric 类型
// 第一次参数 obj 的泛型是 Type,第二个参数 cache 的泛型是 Cache
// return 泛型是 Cache
function addTypedObjectToCache<Type, Cache extends CacheHostGeneric<Type>>(obj: Type, cache: Cache): Cache {
cache.save(obj);
return cache;
}
// OUTPUT >> save cache: cache content
addTypedObjectToCache('cache content', {
save: x => {
console.log('save cache: ' + x);
}
});
interface AnyObjectButMustHaveName {
name: string
[key: string]: any // 其他自定义字段,类型不限 any
}
const printFormattedName = (input: AnyObjectButMustHaveName) => {
console.log(input);
}
printFormattedName({name: "joey"})
printFormattedName({name: "joey", age: 23})
printFormattedName({name: "joey", age: 23, sex: 'female'})
// 同一个入参,支持不同类型
const boolOrNumberFunction = (input: boolean | number) => {}
interface BoolOrNumberOrStringFunction {
/** Takes a bool, returns a bool */
(input: boolean): boolean
/** Takes a number, returns a number */
(input: number): number
/** Takes a string, returns a bool */
(input: string): boolean
}
// 在 ts 运行即使函数不存在,有 declare 会告诉 ts 这是存在的(注意:declare 没有赋值函数体,在运行 js 还是会报错的)
// declare 去掉后,由于 boolOrNumberOrStringFunction 只声明了类型,没有具体的函数体,TS 编译时会报错
declare const boolOrNumberOrStringFunction: BoolOrNumberOrStringFunction
const boolValue = boolOrNumberOrStringFunction(true)
const numberValue = boolOrNumberOrStringFunction(12)
const boolValue2 = boolOrNumberOrStringFunction('string')
优势:
npm install -g typescript
TS 并不能原生地在浏览器或者 node 环境运行,需要被编译为原生的 JS 后,再运行。
tsc demo.ts
OUTPUT >> demo.js