В потоке я могу определить динамический литеральный тип следующим образом:
const myVar = 'foo'
type X = {
[typeof myVar]: string
}
const myX: X = { foo: 1 } // will throw, because number
const myX: X = { foo: 'bar' } // will not throw
Я пытаюсь сейчас преобразовать некоторый код в машинописный текст, где этот синтаксис невозможен. Тем не менее, я не могу понять, как это сделать в машинописи. Вот код, с которым я работаю (уже частично переведен на машинопись):
type Theme = {
fontSizes: number[]
}
type SystemObj = {
prop: string,
cssProperty?: string,
}
type Props<T> = T & {
theme: Theme,
}
const style = <X>({
prop,
cssProperty,
}: SystemObj) => {
const cssProp = cssProperty || prop
return (props: Props<{
[typeof cssProp]: X
}>) => {
return props
}
}
const fontSize = style<number>({
prop: 'fontSize',
})
fontSize({
fontSize: 2,
theme: {
fontSizes: [12, 14, 16],
}
})
В настоящее время выбрасывает (со всеми опциями, включенными на игровой площадке)
Argument of type '{ fontSize: number; theme: { fontSizes: number[]; }; }' is not assignable to parameter of type '{ theme: Theme; }'.
Object literal may only specify known properties, and 'fontSize' does not exist in type '{ theme: Theme; }'.
EDIT:
Итак, я заставил его работать, именно так, как я хочу, чтобы он работал:
type Theme = {
fontSizes: number[]
}
type SystemObj = {
prop: string,
cssProperty?: string,
}
type Props = {
theme: Theme,
}
const style = <X extends string, Y>({
prop,
cssProperty,
}: SystemObj) => {
const cssProp = cssProperty || prop
return (props: Props & { [K in X]: Y }) => {
return props
}
}
const fontSize = style<'fontSize', number>({
prop: 'fontSize',
})
fontSize({
fontSize: 123,
theme: {
fontSizes: [12, 14, 16],
}
})
Можно ли здесь избавиться от части <'fontSize'
? * 1018
const fontSize = style<'fontSize', number>({
prop: 'fontSize',
})
и просто введите это как
const fontSize = style<number>({
prop: 'fontSize',
})
работает именно так, как я хочу, чтобы он работал, просто интересно, смогу ли я удалить здесь дублирование (потому что prop: 'fontSize'
уже определяет ключ). Это приводит к моему первоначальному вопросу, как я могу определить значение fontSize
здесь как ключ внутри моего типа.