TypeScript:让库的用户定义类型
假设我有一个简单的状态管理库,它看起来像:TypeScript:让库的用户定义类型,typescript,typescript-generics,Typescript,Typescript Generics,假设我有一个简单的状态管理库,它看起来像: var appState; export const createState = (obj) => { appState = obj; } export const getStore = (store) => { return appState[store]; } 在TypeScript中,我希望库的用户能够定义他们的状态类型,例如: interface DrawerState { open: boolean } int
var appState;
export const createState = (obj) => {
appState = obj;
}
export const getStore = (store) => {
return appState[store];
}
在TypeScript中,我希望库的用户能够定义他们的状态类型,例如:
interface DrawerState {
open: boolean
}
interface ModalState {
open: boolean,
title: string
}
interface AppState {
drawer: DrawerState;
modal: ModalState;
}
TS能够根据传入的字符串(我们假设可以静态确定)确定getState
的返回类型
谢谢。您正在寻找名为“泛型”的打字脚本功能
导出函数createState(state:state):state{
// ↑ ↑ ↑
//(泛型)(泛型的用法)
返回状态
}
接口MyState{
a:布尔型
b:号码
}
const state=createState({a:true,b:1})
// ↑
//(指定要使用的类型)
//论点必须符合MyState,
//返回值的类型为MyState
好的,谢谢,但最终我想将我的私有appState
变量定义为泛型类型。。。不确定这是否可行。当我将创建的JS库转换为TS:时,出现了此问题。基本上,我希望能够在TS中定义我的状态结构,并让getState
和setState
知道返回类型。不过,这可能需要重新编写API。@kmurph79“我的私有appState”-您需要以不同的方式思考此问题-如果appState
是私有的(不可公开访问),则不需要将其与公共类型相关联-如果消费者需要appState
以获得正确的类型,这意味着他们直接与it进行交互,这是不允许的things@kmurph79-此外,使用模块级状态(如您的appState)总是一种不好的模式,因此,请定义一个采用泛型类型的类,并使appState
成为该类的私有成员-class StateDealer{private-appState:State;}
-避免全局/模块级变量将改进您的体系结构,并使其封装、可隔离、可测试。谢谢,我将尝试按照您的建议重新设计内部构件。
const appState: AppState = {
drawer: {open: false},
modal: {open: false, title: 'the modal'}
};
const store = createStore(appState)
// I want TS to "know" that drawerState is of type DrawerState here!
const drawerState = getState('drawer');
export function createState<State>(state: State): State {
// ↑ ↑ ↑
// (generic type) (usage of generic)
return state
}
interface MyState {
a: boolean
b: number
}
const state = createState<MyState>({a: true, b: 1})
// ↑
// (specify which type to use)
// the argument must conform to MyState,
// and the return value is of type MyState