2

This is a bit of a strange question, but I still got curious of it's possible.

I have a JSON structure from an API that defines a map like this:

"sizes: {
    "thumbnail": "xxxx",
    "thumbnail-width: 150,
    "thumbnail-height: 150,
    "medium: "xxx",
    "medium-width": 500,
    "medium-height": 500,
    ...
}

The names is somewhat predefined, but not really.

My question is if it's possible to define any property that ends with -width or -height to number and everything else as string. Like a regex (.*)-(width|height): number.

TypeScript can do all kind of magic stuff, but can it do something like this?

3 Answers 3

3

Right now, as of TS4.1, there is no specific, concrete type in TypeScript (let's call it Values) which represents the values assignable to that values property. For the record, I'm interpreting this as: any string key is acceptable; if the key ends with -width or -height, the property must be a number; otherwise it must be a string. There is no requirement that such keys must show up as triplets; for example, if "key" is a key, then it is not required that "key-height" or "key-width" be present.

Perhaps when microsoft/TypeScript#42192 gets addressed you'll be able to use "pattern" template literals (as implemented in microsoft/TypeScript#40598) of the form `${string}-width` as keys. For now you cannot.

UPDATE for TS4.4: even with pattern template literal index signatures as implemented in microsoft/TypeScript#44512, you can't make a specific type for Values. You can now represent the part where arbitrary strings ending in -height or -width must be number:

type NumericValues = {
  [key: `${string}-${"height" | "width"}`]: number; 
}

but there's no way to represent the "everything else needs to be a string" constraint... see microsoft/TypeScript#17867. So the following doesn't work:

type BadValues = {
  [key: `${string}-${"height" | "width"}`]: number; // error! incompatible
  [key: `${string}`]: string; // can't say "everything else" here
}

Oh well.


So you can only represent your restriction as a generic constraint, of the form Values<K> for an appropriate K:

type Values<K extends string> = {
  [P in K]: P extends `${string}-${"height" | "width"}` ? number : string
};

If K is the set of string-valued keys in Values<K>, then each property value must be either a number or a string depending on whether or not K ends in "-height"/"-width".

Instead of being forced to annotate a value as type Values<K> for some concrete K, you could use a helper function to make the compiler infer K for you:

const asValues = <K extends string>(values: Values<K>) => values;

Let's try it:

const sizes = asValues({
  "thumbnail": "xxxx",
  "thumbnail-width": 150,
  "thumbnail-height": 150,
  "medium": "xxx",
  "medium-width": 500,
  "medium-height": 500,
}); // okay

const badSizes = asValues({
  "toenail": 123, // error! Type 'number' is not assignable to type 'string'
  "toenail-width": 456,
  "psychic": "yyy",
  "psychic-height": "tall" // Type 'string' is not assignable to type 'number'
})

Looks good. sizes is accepted, but badSizes results in errors on the properties whose types are incorrect.


Of course the fact that we're using generics means that you have to drag around the generic type parameter K everywhere you want to enforce this restriction. This could become unwieldy if used for your whole code base. Instead you might want to just use Values<K> to validate object literals passed-in, and then when you manipulate them you widen to the closest specific type that TypeScript can represent, like a string-indexable type whose properties are string | number:

type WideValues = { [k: string]: string | number };
const wideValues: WideValues = sizes; // okay

So you use Values<K> for validation, and WideValues for manipulation afterward.


Playground link to code

1

From typescript 4.1 it is possible, using literal types. An example:

type AddSuffixToEachProps<T, Suffix extends string, Value extends any> = T & {
    [P in keyof T as `${string & P}-${Suffix}`]: Value
}

This is a type that accept some sort of schema, and add a suffix for each of those props.

Usage:

type Result = AddSuffixToEachProps<{
    foo: string,
    bar: string[]
}, 'width', number>

const test: Result = {
    foo: 'some string',
    "foo-width": 123, // required
    bar: ['one', 'two', 'three'],
    "bar-width": 456 // required
}
3
  • This works if the prefixes are known in advance but the question implies that they are not (or “not really” in any case).
    – jcalz
    Feb 13, 2021 at 17:45
  • Kind of thought Record<${string}-width` | ${string}-height, number>` would have worked, but it doesn't.
    – Oblosys
    Feb 13, 2021 at 17:48
  • Very cool, but only works if the keys are known at compile time, and in that case I could as well define the width and height property. Feb 13, 2021 at 18:52
0

No, it's not possible.

Because

An index signature parameter type must be either 'string' or 'number'.

We can't set type ${string}-width or ${string}-height as a key type of sizes.

3
  • Don't think that explains it as type T = {[x in `${string}-width` | `${string}-height`]: number} compiles just fine, but somehow resolves to T = {}, which seems buggy to me.
    – Oblosys
    Feb 13, 2021 at 18:13
  • Yes, seems buggy to me too. I think this feature is not fully supported yet.
    – glinda93
    Feb 13, 2021 at 18:15
  • Yeah, it's a known issue at microsoft/TypeScript#42192
    – jcalz
    Feb 13, 2021 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.