TypeScript:让库的用户定义类型
TypeScript: letting users of a library define types
假设我有一个简单的状态管理库,如下所示:
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
的return类型(我们假设可以静态判断)
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');
谢谢。
您正在寻找一个名为 "generics"
的打字稿功能
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
假设我有一个简单的状态管理库,如下所示:
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
的return类型(我们假设可以静态判断)
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');
谢谢。
您正在寻找一个名为 "generics"
的打字稿功能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