有办法键入Symbol.for
吗?
a.ts
------
const sym = Symbol.for('sym');
interface I {
[sym]: number
}
export declare function f(i: I): void;
b.ts
------
const sym = Symbol.for('sym');
export class C {
get [sym]() {
return 1;
}
}
c.ts
------
import { C } from 'b';
import { f } from 'a';
const c = new C();
f(c); // Type error
目前正在使用Typescript 3.6,所以我不知道它的后续版本可能会支持它。
这很有效,但看起来像是一个拼凑。。
types/sym.d.ts
------
declare module 'sym' {
const sym: unique symbol;
export type Sym = typeof sym;
}
a.ts
------
import type { Sym } from 'sym';
const sym: Sym = Symbol.for('sym') as Sym;
interface I {
[sym]: number
}
export declare function f(i: I): void;
b.ts
------
import type { Sym } from 'sym';
const symy: Sym = Symbol.for('sym') as Sym;
export class C {
get [sym]() {
return 1;
}
}
c.ts
------
import { C } from 'b';
import { f } from 'a';
const c = new C();
f(c); // Type error
我很想看看是否有更干净的方法可以做到这一点,而不必导出接口并让C实现