类型不能出现在表达式中。您希望用此类型声明常量,因为该常量已声明并且将在运行时存在:
declare module "test" {
export const someType: {
val1: 'myvalue',
val2: 'myothervalue',
}
type someTypeValue = typeof someType[keyof typeof someType];
export function sampleFunction(param1: someTypeValue): number;
export function sampleFUnction2(param1: someTypeValue): number;
}
// usage.ts
import { sampleFunction, someType} from 'test';
console.log(sampleFunction(someType.val1));
console.log(sampleFunction('myvalue')); // will also work
上面的示例直接公开const,并允许您传入任何值为
sampleType
。
还可以使用实际枚举对此进行建模,该枚举将隐藏常量中的字符串值:
declare module "test" {
export enum someType {
val1 = "myvalue",
val2 = 'myothervalue'
}
export function sampleFunction(param1: someType): number;
export function sampleFUnction2(param1: someType): number;
}
// usage.ts
import { sampleFunction, someType} from 'test';
console.log(sampleFunction(someType.val1));
console.log(sampleFunction('myvalue')); // error
取决于您想要实现什么,任何一个版本都可以工作