typescript - 函数参数解构的 TSLint 错误

标签 typescript parameter-passing tslint destructuring

我想删除我在以下(对象解构参数中)遇到的 tslint 错误:

export function renameProperty(
    oldProp: string,
    newProp: string,
    {[oldProp]: old, ...others}
): any {
    return {
        [newProp]: old,
        ...others
    };
}

我得到的错误在第 5 行:

TSLint:预期参数:'{[oldProp]: old, ...others}' 有一个类型定义 (typedef)

当然,我可以执行以下操作,但我宁愿简单地执行满足 Typescript 键入要求的操作。

export function renameProperty(
    oldProp: string,
    newProp: string,
    // tslint:disable-next-line:typedef
    {[oldProp]: old, ...others}
): any {
    return {
        [newProp]: old,
        ...others
    };
}

关于如何在 {[oldProp]: old, ...others} 行中键入 def 的任何答案?

最佳答案

有趣的问题,但似乎没有明确的答案。但这是一种尝试:

export function renameProperty<
    T extends {},
    OP extends keyof T,
    NP extends string,
    R = Omit<T, OP> & Record<NP, T[OP]>
>(oldProp: OP, newProp: NP, { [oldProp]: value, ...others }: T): R {
    return {
        [newProp]: value,
        ...others
    } as any; // *
}

这有好处,返回正确的类型,删除 oldProp 并添加 newProp

const c = renameProperty("foo", "bar", { foo: 1, baz: "spam", holy: "grenade" });
console.log(c.foo, c.bar, c.baz, c.holy);
    /// complains here, that 'foo' is not available in c
    /// typeof c.bar === "number"

* 不幸的是,TS 无法从 {[newProp]: value} 中推断出正确的类型,结果类型是 { [x: string]: ... } 非常可怕因为需要任何(至少我没有找到删除它的方法 - 不确定这是错误还是限制)。

省略:Exclude property from type

关于typescript - 函数参数解构的 TSLint 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266022/

相关文章:

typescript - 在界面中,如果另一个属性为 `true` 或 `false`,则在两种类型之间切换

javascript - Typescript AngularJS 访问表单对象

reactjs - 将属性子集传输到 Typescript React 中的子组件

typescript - '+' 操作的操作数必须是两个字符串或两个数字。考虑使用模板文字 @typescript-eslint/restrict-plus-operands

node.js - 当返回 promise 而不是流时,Gulp 结束得太早

javascript - 使用 Typescript 异步进行 Mocha API 测试

PHP:通过引用的可变长度参数列表?

python - 我应该在函数调用的最后一个参数之后添加一个逗号吗?

javascript - 将文本传递到在 JS 函数中打开的弹出窗口

angular - Tslint --exclude 不起作用