#Infer string literal object keys

1 messages · Page 1 of 1 (latest)

solid lindenBOT
#
Frosk#6439

Preview:```ts
const fields = {
[field0]: 1,
}
type Fields = typeof fields
// ^?

const fieldsLiteral = {
[field${0}]: 1,
}
type FieldsLiteral = typeof fieldsLiteral
// ^?
// Note the {[x: string]: number} type

const fieldsLiteralAsConst = {
[field${0} as const]: 1,
...```

hasty lichen
#

Is it possible to get {field0: number} through narrowing instead of writing as const?

#

More specifically, I have something like

const fields = {
  [`field${0}a`]: 'a',
  [`field${0}b`]: 1,
}

// --> typeof fields = {
    [x: string]: string | number;
} 
//I would like it to not create a union like so:

const fieldsAsConst = {
  [`field${0}a` as const]: 'a',
  [`field${0}b` as const]: 1,
}

// --> typeof fieldsAsConst = {
    field0a: string;
    field0b: number;
}
north glacier
hasty lichen
#

you are likely right, but I was hoping to avoid having the user write additional syntax that could be easily forgotten

north glacier
#

then you'd need a function

solid lindenBOT
#
function foo<T extends { [k: string]: unknown; }>(obj: T) { return obj; }
const fields = foo({
//    ^? - const fields: {
//        [x: string]: string | number;
//    }
  [`field${0}a`]: 'a',
  [`field${0}b`]: 1,
});
north glacier
#

dang

solid lindenBOT
#
const what = {
//    ^? - const what: {
//        readonly [x: string]: "a" | 1;
//    }
  [`field${0}a`]: 'a',
  [`field${0}b`]: 1,
} as const;
north glacier
#

ouch

#

so i guess it's not possible

hasty lichen
#

yeah each key must be as const

north glacier
#

yeah that kinda sucks