简体   繁体   English

setter 中的代理属性从不输入

[英]Proxy property in setter has never type

With TypeScript 4.5.4 (current latest) and currently Nightly version, this code (see below or in TypeScript playground ) is throwing error Type 'any' is not assignable to type 'never'.(2322) for the version 1,2,3,4 yet for version 5 and 6 no error is reported.使用 TypeScript 4.5.4(当前最新)和当前 Nightly 版本,此代码(见下文或TypeScript 操场)抛出错误Type 'any' is not assignable to type 'never'.(2322)版本 1、2 3,4 版本 5 和 6 尚未报告错误。 If we remove one of the num prop or str , all the errors are gone.如果我们删除num prop 或str之一,所有错误都消失了。

Is there an explanation for this design?这个设计有解释吗?

const myObj = {
  num: -1,
  arr: [1, 2, 3],
  str: '',
};

const proxy = new Proxy(myObj, {
  set(target, prop: keyof typeof myObj, value) {
    /* none of these works */
    // Ver. 1
    if (prop in target) target[prop] = value;
    // Ver. 2
    target[prop] = value;
    // Ver. 3
    target[prop as keyof typeof myObj] = value;
    // Ver. 4
    switch (prop) {
      case 'num':
      case 'str':
        target[prop] = value;
        break;
    }

    /* while these works */
    // Ver. 5
    switch (prop) {
      case 'num':
        target[prop] = value;
        break;
      case 'str':
        target[prop] = value;
        break;
    }
    // Ver. 6
    switch (prop) {
      case 'num':
        target[prop] = value;
        break;
      default:
        target[prop] = value;
        break;
    }

    return true;
  },
});

console.log('proxy : ', proxy);

Summarized总结

Writing produces type intersection in TS.写作在 TS 中产生类型交集。

Detailed详细的

This is a copy of the answer from the official repo microsoft/TypeScript#47295 , this is a functionality that "work as intended".这是官方 repo microsoft/TypeScript#47295答案的副本,这是“按预期工作”的功能。

In most of your setups, the type of prop is not narrowed down from "num" | "str" | "arr"在您的大多数设置中, prop的类型不会从"num" | "str" | "arr"缩小范围。 "num" | "str" | "arr" "num" | "str" | "arr" ; "num" | "str" | "arr" ; since you're writing to target[prop] rather than reading from it, that produces an intersection (not a union) of all the possible types it could refer to.由于您正在写入target[prop]而不是从中读取,因此会产生它可以引用的所有可能类型的交集(不是联合)。 If there's no overlap, the intersection collapses to never , because there's no possible value that works for all of them.如果没有重叠,则交集将折叠为never ,因为没有可能的值适用于所有这些。

This answer is created to close the question.创建此答案是为了结束问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM