我正在try 创建一个命名空间/类/接口/类型(无论我需要哪一个,我已经研究了所有它们,似乎没有一个能够满足我的需要),它声明了一些properties和methods类型.但其中也有子类型,如Character.Stats
或Character.Currency
.一百零五
我需要如何格式化/布局我的打字文件才能使这classes.ts
个个文件成为有效的打字脚本?
// statement to import Character type
class Player implements Character {
constructor (
public name: string, // a property
public stats: Character.Stats, // a property with a subtype typing
public currency: Character.Currency
) {
this.name = name
this.stats = stats
this.currency = currency
}
attack(target: Player) { // parameter is typing of its own class
console.log(`Attacked ${Character.name}`)
}
}
目前,使用TypeScrip还能做到这一点吗?
以下是我当前的测试代码库:
types/items.ts
个
export interface Type {
name: string,
sprite: string,
}
types/characters.ts
个
import * as Classes from "../classes";
export interface Stats {
health: number,
attack: number,
defence: number,
}
export interface Currency {
gold: number,
ridium: number
}
export interface Type {
name: string,
stats: Stats
currency: Currency
announce(sentence: string): void,
attack(target: Type): void,
heal(item: Classes.HealingItem): void
}
classes.ts
个
import * as Characters from "./types/characters";
import * as Items from "./types/items"
export class Character implements Characters.Type {
constructor(
public name: string,
public stats: Characters.Stats,
public currency: Characters.Currency
) {
this.name = name;
this.stats = stats
this.currency = currency
}
announce(sentence: string) {
console.log(`I, ${this.name}, ${sentence}`)
}
attack(target: Character): void {
this.announce(`am going to attack ${target.name}`)
}
heal(item: HealingItem) {
this.stats.health += item.healthPoints;
this.announce(`used ${item.name} to heal my hp from ${this.stats.health - item.healthPoints} to ${this.stats.health}`)
}
}
export class HealingItem implements Items.Type {
constructor(
public name: string,
public sprite: string,
public healthPoints: number
) {
this.name = name
this.sprite = sprite
this.healthPoints = healthPoints
}
}
index.ts
个
import * as Classes from "./classes";
const hero = new Classes.Character("Bob", // name
{ // stats
health: 100,
attack: 10,
defence: 25
},
{ // currency
gold: 50,
ridium: 0
}
)
const apple = new Classes.HealingItem("Apple", "./sprites/apple.sprite", 25);
hero.heal(apple);
hero.attack(hero);
当前的代码运行得很好,但当前的布局似乎会在future 引发问题.由于Items.Type
/Characters.Type
如果这是我能得到的最接近我想要的结果,那么...
简而言之...
我想要这样的东西
interface B {
x: string
}
namespace A {
export type v1 = number
export type v2 = boolean
export type v3 = B
}
let p: A = {
v1: 9,
v2: true,
v3: { x: "some string" }
};
let q: A.v1 = 2;
let r: A.v2 = false;
let s: A.v3 = { x: "strung" };
这不是有效的代码,因为let p: A
不允许将命名空间作为类型,但希望这就是我要实现的目标.