我正试图构建一个函数,该函数通过显式传递类型的函数返回类型化对象
https://stackblitz.com/edit/typescript-uahcrj?file=types.ts
export interface M<TS = any> {
name?: string;
state: TS;
}
export const createModel = <TS>() => <
TM extends M<TS>
>(
mo: TM
): TM => mo
export type SharksType = {
values: number[]
amount: number
}
export const sharks = createModel<SharksType>()({
state: {
values: [],
amount: 1,
},
})
实际上,量是正确推断的,但像number[]
这样的复杂状态,它的定义就像任何[],
如何对状态的每个键动态执行as?
state: {
values: [] as number[],
amount: 1 as number,
},
以下是我在坚持您的示例的同时如何重构它——我认为您可以将其简化很多。以下是一个代码沙盒:https://codesandbox.io/s/6xd37?file=/index.ts:0-363
主要的事情是键入createModel函数。在依赖推理之前,您需要定义函数是泛型的才能使用类型参数。
interface CommonModel<T> {
name?: string;
state: T;
}
type SharksType = {
values: number[]
amount: number
}
const createModel: <T>() => (mo: CommonModel<T>) => CommonModel<T> = () => (mo) => mo;
const sharks = createModel<SharksType>()({
state: {
values: [],
amount: 1,
},
});
sharks.state.values.push('str'); // error