打字稿推断无法正常工作

问题描述

我正在尝试构建一个通过显式传递类型的函数返回有类型对象的函数

https://stackblitz.com/edit/typescript-uahcrj?file=types.ts

<mat-checkbox formControlName="form">
  Form
</mat-checkbox>

实际上,可以正确推断金额,但是像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,},}) 这样的复杂状态的定义类似于any [],

我该如何动态地对状态键as进行每个操作?

number[]

解决方法

在坚持您的示例的同时,这就是我如何重构它的方法-我认为您可以将其简化很多。这是以下代码和框: https://codesandbox.io/s/6xd37?file=/index.ts:0-363

最主要的是键入您的createModel函数。在依赖推理之前,您需要定义该函数是通用的以使用type参数。

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...