gpt4 book ai didi

typescript - typescript 中括号表示法的类型

转载 作者:行者123 更新时间:2023-12-04 10:15:08 28 4
gpt4 key购买 nike

我正在尝试为一些常规状态更新创建一个 redux 操作,并想知道是否可以使类型适用于括号表示法:

interface IThing {
someProp: string;
otherProp: boolean;
}

const state = {
thing: {
someProp: 'prop',
otherProp: true,
} as IThing
}

const action = { name: 'someProp' as keyof IThing, value: 'someValue' as any }

// gives typescript error: Type 'any' is not assignable to type 'never'
state.thing[action.name] = action.value;

最佳答案

这里的问题是,如果您通过动态属性名称分配值,那么右侧的值需要可分配给您可能命名的任何属性。在这种情况下,这意味着它必须可以分配给 stringboolean ,这意味着它必须是 never 类型(因为这两种类型没有共同的值)。

解决方案是使用泛型类型,以便您可以将属性名称限制为类型 K ,您分配的值可以是 IThing[K] 类型这不一定是 never .下面是一个例子:

interface IAction<K extends keyof IThing> {
name: K;
value: IThing[K];
}

function assign<K extends keyof IThing>(thing: IThing, action: IAction<K>): void {
thing[action.name] = action.value;
}

const action = { name: 'someProp', value: 'someValue' } as const;
assign(state.thing, action); // ok

Playground Link

关于typescript - typescript 中括号表示法的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61099722/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com