如何解决如何使用 TypeScript 的模板文字类型改进范围字典的类型检查?
我有不同的 json 翻译文件,我想使用 TypeScripts 4.1 Template Literal Types 进行静态输入。 There is a similar question 但我想为此添加范围。我的代码如下:
type dict = typeof import('./login/en.json') | typeof import('./register/en.json')
type Scopes = 'login' | 'register'
type GetDictValue<T extends string,O> = T extends `${Scopes}_${infer A}.${infer B}`
? A extends keyof O
? GetDictValue<B,O[A]>
: never
: T extends keyof O
? O[T]
: never
type CheckDictString<T extends string,O> = T extends `${Scopes}_${infer A}.${infer B}`
? A extends keyof O
? `${Scopes}_${A}.${Extract<CheckDictString<B,O[A]>,string>}`
: never
: T extends keyof O
? T
: never
declare function t<P extends string>(p: P & CheckDictString<P,dict>): GetDictValue<P,dict>
其中 login/en.json
具有以下内容:
{
"foo": "Foo"
}
还有register/en.json
:
{
"bar": "Bar"
}
然而这行不通。这将是预期的结果:
t('login_foo') // OK
t('login_bar') // KO
t('register_bar') // OK
t('register_foo') // KO
t('foo') // KO
t('bar') // KO
我怎么能做到这一点?可能吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。