为什么typescript对在接口中使用自定义符号有限制?
下面是一个简单的程序:为什么typescript对在接口中使用自定义符号有限制?,typescript,typescript2.0,Typescript,Typescript2.0,下面是一个简单的程序: const mySymbol = Symbol(); interface Fails { [mySymbol]: boolean; } interface Succeeds { [Symbol.hasInstance]: boolean; } 这是compling的输出: $ tsc --lib es6 odd.ts odd.ts(3,3): error TS1169: A computed property name in an interface must
const mySymbol = Symbol();
interface Fails {
[mySymbol]: boolean;
}
interface Succeeds {
[Symbol.hasInstance]: boolean;
}
这是compling的输出:
$ tsc --lib es6 odd.ts
odd.ts(3,3): error TS1169: A computed property name in an interface must directly refer to a built-in symbol.
错误是可以理解的,只有内置符号可以用作Typescript接口属性类型,但这似乎是一个任意的限制
有人能解释为什么存在这种限制吗?考虑一些代码:
// Implementation not visible to us
declare function getSymbol(): Symbol;
const s1 = getSymbol();
const s2 = getSymbol();
interface Type1 {
[s1]: string;
[s2]: number;
}
这个声明合法吗?让我们问问朋友
Alice说yes,因为getSymbol
每次调用时都返回不同的符号,所以s1
和s2
创建两个单独的属性槽
Bob说no,因为每次调用getSymbol
时总是返回相同的符号,所以s1
和s2
是同一属性的冲突声明
Eve说哈哈哈,因为getSymbol
随机返回两个不同符号中的一个,所以谁知道发生了什么
谁说得对?我不知道。没有人知道。我们都只是猜测,因为我们看不到getSymbol
的实现。即使我们可以,其执行也可能是任意复杂的
此外,即使我们可以描述getSymbol
的行为,我们仍然无法解释这段代码:
// Implementations not visible to us
declare function getSymbol1(): Symbol;
declare function getSymbol2(): Symbol;
const s1 = getSymbol1();
const s2 = getSymbol2();
interface Type1 {
[s1]: string;
[s2]: number;
}
可能
getSymbol1
和getSymbol2
返回相同的符号。也许他们没有。也许他们有时会。谁知道呢?如果没有明确命名单个符号实例的方法,这将是一个无法解决的难题。但是类型系统,尤其是结构系统,在描述实例标识方面非常糟糕。您可以在某个系统中命名每个符号实例,但仍然无法描述在每次调用时返回新符号的函数。一般来说,您将很难使用第一个代码段这样的代码,因为类型系统将假定同一个函数调用两次,会生成两个实际上完全相同的对象。谢谢!这很有道理。不过,可能像hasInstance这样的众所周知的符号是编译器刚刚知道的。我猜在他们被重新分配的地方,他们不会有什么有趣的事情发生。正确-在这方面,Symbol
对象的声明成员被认为是“正常”的