是否有方法将字符串映射到TypeScript中匹配的模板文字类型?
下面是一个例子:
type SomeType<T> = {
[P in keyof T as `as${Capitalize<string & P>}`]: number;
};这应该将x的每个属性都转换为T,并使其成为属性asX。
但是现在我想取一个像foo这样的属性名,并以TypeScript可以检测到的方式将其转换为asFoo。
我希望能够做到这一点:
interface I {
foo: number;
bar: number;
}
const obj: SomeType<I> = {
asFoo: 1,
asBar: 2,
};
const str = 'foo';
// Doesn't work, trying to capitalize str, but TypeScript only sees it as a string
obj[`as${str[0].toUpperCase()}${str.slice(1)}`];我想以某种方式取str和索引obj。这有可能吗?我想我可以拉绳子,但我不想那样做。
目前,我正在通过创建这样一个函数来处理这个问题:
function getProperty(key: string): keyof SomeType<I> {
return key === 'foo' ? 'asFoo' : 'asBar';
}
obj[getProperty('foo')];但我只想看看是否有一个更优雅的解决方案,因为如果有很多属性,这可能会失控。我对TypeScript非常陌生,所以我可能遗漏了一些东西。
发布于 2021-10-28 06:16:02
我通常试图把我的逻辑分解成尽可能小的部分。COnsider这个例子:
type SomeType<T> = {
[P in keyof T as `as${Capitalize<string & P>}`]: number;
};
interface Obj {
foo: number;
bar: number;
}
const obj: SomeType<Obj> = {
asFoo: 1,
asBar: 2,
};
const capitalize = <Key extends string>(key: Key) =>
`${key[0].toUpperCase()}${key.slice(1)}` as Capitalize<Key>
const withPrefix = <Key extends string>(key: Key): `as${Key}` => `as${key}`
const getProperty = <Key extends string>(key: Key) => withPrefix(capitalize(key))
const result = getProperty('foo') // asFoo
const getter = obj[result] // number这一行as${Capitalize<string & P>}由两个操作组成:
as前缀这就是为什么我为此使用了两个函数。
正如您可能已经注意到的,withPrefix和getProperty可能由以下两个部分组成:
import { compose } from 'redux'
const capitalize = <Key extends string>(key: Key) =>
`${key[0].toUpperCase()}${key.slice(1)}` as Capitalize<Key>
const withPrefix = <Key extends string>(key: Key): `as${Key}` => `as${key}`
type Fn =
<Key extends string>(key: Key) => `as${Capitalize<Key>}`
const getProperty =
compose(withPrefix, capitalize) as Fn
const result = getProperty('foo') // asFoo但是它要求您在类型断言中使用额外的compose函数。
您可以了解有关模板文字字符串从医生那里的更多信息。
https://stackoverflow.com/questions/69748381
复制相似问题