首页 > 解决方案 > TypeScript 错误:类型 'string' 不可分配给类型 'number | ""'

问题描述

我是 TypeScript 的新手,我很难理解以下错误。

Type '{ order: string; }[]' is not assignable to type 'TestType[]'.
  Type '{ order: string; }' is not assignable to type 'TestType'.
    Types of property 'order' are incompatible.
      Type 'string' is not assignable to type 'number | ""'.

这是我的测试代码

export enum ACTION_TYPES {
    TEST_ACTION = 'TEST_ACTION',
}


export type TestType = {
    order: number | '';
};

export function TestAction(
    testTypes: TestType[]
): {
    type: ACTION_TYPES.TEST_ACTION;
    testTypes: TestType[];
} {
    return {
        type: ACTION_TYPES.TEST_ACTION,
        testTypes,
    };
}

export type PluginsState = {
    testTypes: TestType[];
};

export type Actions =
    | ReturnType< typeof TestAction >;



const reducer = (
    state: PluginsState = {
        testTypes: [],
    },
    payload?: Actions
): PluginsState => {
    if ( payload && 'type' in payload ) {
        switch ( payload.type ) {
            case ACTION_TYPES.TEST_ACTION:
                return {
                    ...state,
                    testTypes: payload.testTypes,
                };
        }
    }
    return state;
};

export const stub = [
    {
        order: '',
    }
];


const defaultState: PluginsState = {
    testTypes: [],
};


reducer( defaultState, {
    type: ACTION_TYPES.TEST_ACTION,
    testTypes: stub,
} );

这是 TypeScript 游乐场链接

错误来自最后一行testTypes: stub

我很确定我做错了什么,但我不明白为什么''不能与number | ""

是否有解决此错误的方法?

标签: typescript

解决方案


从代码作者的角度来看,您所写的内容是正确的,这应该可以正常工作。但是,Typescript 是这样看待它的(而是推断它):

export const stub = [
    {
        order: '',
    }
];

这本质上是 type: ,这在大多数情况下{order:string}[]都是有意义的。但是,这是您的通用版本,Typescript 不能保证传递的任何内容都会是,您可能会对其进行变异,而 Typescript 仍然必须允许它。所以,它警告你。{order:''}[]{order: number|''}

为了避免这种推断,您可以做两件事:

  1. 将类型显式分配给stubasTestType以便 TypeScript 在不再属于该类型时会出错,如下所示:

    export const stub: TestType[] = [
      {
        order: "",
      },
    ] ;
    
  2. 或者,对可变数组元素执行const 断言,承诺该元素不变,如下所示:

    export const stub = [
      {
        order: "",
      } as const,
    ] ;
    

这是您的工作示例:https ://tsplay.dev/WvpdYN


推荐阅读