【发布时间】:2020-01-25 07:38:45
【问题描述】:
我使用 typescript 和 react hooks 制作了一个名为 risk 的游戏。游戏在某种地图上进行。所以首先我有设计我MapEditor。 Map Editor 的状态是这样的
export interface IMapEditorState {
mousePos: IPoint;
countries: {[k: string]: ICountry};
continents: { [k: string]: IContinent };
}
countries 和 continents 是对象。国家的界面看起来像
//The "name" property and above key will be same in `{[k: string]: ICountry};` will be same
export interface ICountry {
name: string;
border: IDot[];
neighbours: string[];
completed: boolean;
}
现在我做一个减速器功能。对于所有类型的动作,我使用了两个道具name 和data。 name 将始终是 string 并且数据将是取决于 name 的类型
type ActionTypes = {name: "removeCountry", data: string} | {name: "addCountry", data: ICountry};
const reducer = (state: IMapEditorState, action: ActionTypes) => {
...
}
现在查看ActionTypes 中的第一个类型,即{name: "removeCountry", data: string}。在调度方法中,我将使用{name: "removeCountry"},编译器将强制将data 作为string 传递,但它不能是我不想要的任何字符串。我希望我应该只能在IMapEditorState 中传递{[k: string]: ICountry} 的键或ICountry 中的name 的字符串。
有什么方法可以创建一个名为CountryName 的字符串的子类型并使用它
export interface IMapEditorState {
mousePos: IPoint;
countries: {[k: CountryName]: ICountry};
continents: { [k: string]: IContinent };
}
export interface ICountry {
name: CountryName;
border: IDot[];
neighbours: string[];
completed: boolean;
}
type ActionTypes = {name: "removeCountry", data: CountryName} | {name: "addCountry", data: ICountry};
如果你能帮助我,我将非常感激,如果你知道什么是游戏,请给出你对我的数据结构的看法。
【问题讨论】:
-
@CertainPerformance 我已经进一步创建了任何东西。只是想找到更好的方法。
-
@CertainPerformance 考虑
function test(x : CountryName){...}。现在这里我想只能通过ICountry的name属性(暂时忽略对象的键) -
鉴于接口是
name: CountryName;,输入function test(x : CountryName)应该已经要求参数是允许的类型,即CountryName,仅此而已,对吧? -
@CertainPerformance 我还希望
countries的键为CountryName类型。但如果不可能,请解释为什么不能。
标签: javascript typescript react-hooks