【发布时间】:2019-09-24 06:17:51
【问题描述】:
要求:对于传递给createStore 函数的数组中的每个元素,selector 的第二个类型应该与value 的类型匹配。
例如:如果selector 属性的类型为Selector<boolean, number>,则value 属性的类型应为number,与数组类型的其他元素无关。
export type Selector<S, Result> = (state: S) => Result;
export interface SelectorWithValue<S, Result> {
selector: Selector<S, Result>;
value: Result;
}
export interface Config<T, S, Result> {
initialState?: T;
selectorsWithValue?: SelectorWithValue<S, Result>[];
}
export function createStore<T = any, S = any, Result = any>(
config: Config<T, S, Result> = {}
): Store<T, S, Result> {
return new Store(config.initialState, config.selectorsWithValue);
}
export class Store<T, S, Result> {
constructor(
public initialState?: T,
public selectorsWithValue?: SelectorWithValue<S, Result>[]
) {}
}
const selectBooleanFromString: Selector<string, boolean> = (str) => str === 'true';
const selectNumberFromBoolean: Selector<boolean, number> = (bool) => bool ? 1 : 0;
createStore({
selectorsWithValue: [
{ selector: selectBooleanFromString, value: false },
{ selector: selectNumberFromBoolean, value: 'string' } // should error since isn't a number
],
});
这是我第一次尝试修改 Typescript Playground @jcalz provided for the nested array use case:
澄清:以上是我尝试对数组的第二个元素执行错误。但是,它确实出错,但原因是错误的。这是我最初的尝试,根本没有给出错误:
export type Selector<S, Result> = (state: S) => Result;
export interface SelectorWithValue<S, Result> {
selector: Selector<S, Result>;
value: Result;
}
export interface Config<T> {
initialState?: T;
selectorsWithValue?: SelectorWithValue<any, any>[];
}
export function createStore<T = any>(
config: Config<T> = {}
): Store<T> {
return new Store(config.initialState, config.selectorsWithValue);
}
export class Store<T> {
constructor(
public initialState?: T,
public selectorsWithValue?: SelectorWithValue<any, any>[]
) {}
}
const selectBooleanFromString: Selector<string, boolean> = (str) => str === 'true';
const selectNumberFromBoolean: Selector<boolean, number> = (bool) => bool ? 1 : 0;
createStore({
selectorsWithValue: [
{ selector: selectBooleanFromString, value: false },
{ selector: selectNumberFromBoolean, value: 'string' } // should error unless value is a number.
//the passed `selector` property is type Selector<boolean, number>, therefor, the `value` should be a number
//the second type of the selector property should match the type of value
],
});
【问题讨论】:
-
在“
// should error since isn't a number”中,它确实错误。你能做一些不会出错但应该出错的东西吗?否则我很难跟上。 -
感谢您的浏览!我在上面添加了说明。
标签: typescript typescript-generics