gpt4 book ai didi

javascript - 我们可以在 Typescript 声明文件中使用全局符号吗?

转载 作者:行者123 更新时间:2023-11-30 19:32:04 24 4
gpt4 key购买 nike

我正在尝试实现类似的功能,但不确定是否可行。我认为 Typescript 只允许唯一符号,而不是全局符号。这是正确的吗?

有没有更好的方法来实现使用全局符号?

// sample.d.ts
const mySymbol = Symbol.for('internal.symbol')

interface Sample{
[mySymbol]: string
a: number
b: number
}

// sample.js
class SampleClass implements Sample {
[mySymbol]: string
a: number
b: number

constructor(a: number, b: number){
this.a = a;
this.b = b;
this[mySymbol] = `${a}-${b}`
}
}

let mySample = new SampleClass(1, 2)

有没有办法做到这一点? mySymbol 可以(理想情况下)是一个全局符号,它也将被其他对象使用,因此如果可以实现的话,它可以单独定义。

最佳答案

我是这样实现的。

// misc.ts
export const mySymbol = Symbol.for('internal.symbol')

// sample.d.ts
import {mySymbol} from './misc'

export as namespace Sample
export = Sample
interface Sample{
[mySymbol]: string
a: number
b: number
}

// sample.js
class SampleClass implements Sample {
[mySymbol]: string
a: number
b: number

constructor(a: number, b: number){
this.a = a;
this.b = b;
this[mySymbol] = `${a}-${b}`
}
}

let mySample = new SampleClass(1, 2)

一旦 mySymbol 被导入到声明文件中,它就会变成一个模块。因此,它需要使用 export = Sampleexport as namespace Sample 专门导出。参见 sample module.d.ts .

关于javascript - 我们可以在 Typescript 声明文件中使用全局符号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56333076/

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