我正在尝试在 TypeScript 中实现一个类,我可以选择在构造函数中传递一个变量 ( converters
),这将定义 Generic
的类型这是在该类中定义的。
在下面的文件中,您可以看到我正在从另一个类导入和导出类型,我正在创建一个 Record
来自名为 Converters
的类型我正在创建类型 Names
和Value
其中类型是根据是否传递给它的泛型(传递给实现中的类)来定义的,并且类型为 Converters
.
那么无论类 Service
收到converters
作为参数 Names<C>
和Value<C, N>
将返回不同的类型。
/**
* importing and exporting some types
**/
import { Converter } from "./characteristic";
export { Converter } from "./characteristic";
/**
* defining some types myself
**/
export type Converters = Record<string, Converter<any>>;
export type Names<C> = C extends Converters ? keyof C : (string | number);
export type Value<C, N extends Names<C>> = C extends Converters
? ConvertersValue<C, N>
: Buffer;
export type ConvertersValue<
C extends Converters,
N extends Names<C>
> = C[N] extends Converter<infer V> ? V : never;
/**
* implementation
**/
export default class Service<C> {
private converters?: Converters;
constructor(converters?: C extends Converters) {
// ^^^^^^^^^^
// an error occurs here
this.converters = converters;
}
public async read<N extends Names<C>>(name: N): Promise<Value<C, N>> {
throw new Error("Not implemented yet");
}
}
这很好用。但我想TypeGuard
可以传递给构造函数的参数,这样我可以确保用户不能传递任何内容( undefined
)给它,但如果传递一些东西给它,它必须是 Converters
类型。所以我写了
constructor(converters?: C extends Converters) {}
但这会抛出一个 typescript
type Converters = { [x: string]: Converter<any>; } Parameter 'converters' of constructor from exported class has or is using private name ''.ts(4063) Parameter 'converters' of constructor from exported class has or is using private name ''.ts(4063)
我正在导出我正在使用的所有类型,但 TypeScript 提示我缺少一个空字符串,因此我不确定出了什么问题。
编辑,奇怪的是,当我使用它作为构造函数时也会发生这种情况
constructor(converters: C extends string) {
this.converters = converters;
}
最佳答案
对于发现此问题的其他人,请在函数签名中使用泛型之前声明它,例如。
constructor<C extends string>(converters?:C) { .... }
不是
constructor(converters?:C extends string) { .... }
我在接口(interface)声明中使用它:
interface Foo {
myMethod<T extends MyAbstractClass>(obj:T):void;
}
关于typescript - 导出类的构造函数参数具有或正在使用私有(private)名称 ''(空字符串)ts(4063),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57852248/