1.文档 https://www.tslang.cn/docs/handbook/advanced-types.html http://ts.xcatliu.com/
2.步骤 全局安装ts-node包 javascript npm install typescript ts-node @types/node@* -g
直接运行自己的ts文件 tsc index.ts
然后可能会报错 可能是vscode策略受限制,那么以管理员身份重新打开vscode,到控制台依次输入:
get-ExecutionPolicy 显示restricted:表示是受限制的
set-ExecutionPolicy RemoteSigned
get-ExecutionPolicy 显示RemoteSigned
解决完报错之后,回到这一步,控制台输入
tsc index.ts
会在当前文件夹生成相应js文件,这个时候可以通过node greeter.js 运行这个文件 或者在vscode上安装Code Runner插件,直接找到生成的js,右键选择 run code运行。
3.策略模式的一个例子
类图 文件目录结构
import IFlyBehavior from './IFlyBehavior'
import IQuackBehavior from './IQuackBehavior'
abstract class Duck{
protected flyBehavior:IFlyBehavior;
protected quackBehavior:IQuackBehavior;
public Swim() :string{
return '所有鸭子都可以游泳!'
}
public performQuack():string {
return this.quackBehavior.Quack()
}
public performFly():string {
return this.flyBehavior.Fly()
}
public setQuackBehavior(qck :IQuackBehavior) {
this.quackBehavior = qck
}
public setFlyBehavior(fly:IFlyBehavior) {
this.flyBehavior = fly
}
public abstract Display()
}
export default Duck;
import Duck from './duck'
import FlyWithWings from './FlyWithWings'
import Quack1 from './Quack1'
class RedheadDuck extends Duck{
constructor() {
super()
super.setQuackBehavior(new Quack1())
super.setFlyBehavior(new FlyWithWings())
}
public Display():string {
return '我是一只红头鸭'
}
}
export default RedheadDuck
interface IQuackBehavior
{
Quack():string;
}
export default IQuackBehavior
interface IFlyBehavior
{
Fly():string;
}
export default IFlyBehavior
import IFlyBehavior from './IFlyBehavior'
class FlyWithWings implements IFlyBehavior{
public FlyWithWings() {}
public Fly():string {
return '我飞啦';
}
}
export default FlyWithWings
import IQuackBehavior from './IQuackBehavior'
class Quack1 implements IQuackBehavior{
public Quack():string {
return '呷呷';
}
}
export default Quack1
import RedheadDuck from "./redheadDuck";
class Program {
public static Main(args:string[]):void{
let redheadDuck:RedheadDuck = new RedheadDuck()
console.log(redheadDuck.Display() + '#' + redheadDuck.Swim() + '#' + redheadDuck.performFly() + '#' + redheadDuck.performQuack());
}
}
Program.Main([])
输出:
|