Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a record-like type with a specific value type for some keys

My goal is to define a record-like type (with an arbitrary set of keys), but where some of those keys are reserved for a specific value type.

I'd create an object something like:

const o: TRec = {
    text: "abc",
    width: 123,
    height: 456,
    //...whatever string key having a numeric value
}

That is, "text" must be the only key bound to a string, whereas any other key is numeric.

However, I can't find a way to define TRec.

So far, I tried the below types, but none of them is acceptable for the above assignment. The compiler shows this error:

Property 'text' is incompatible with index signature. Type 'string' is not assignable to type 'number'.

type TRec = Record<string, number> &{
    text: string;
}

type TRec = {
    [key: string]: number;
    text: string;
}

type TRec = Omit<Record<string, number>, "text"> & {
    text: string;
}

Any clue?

like image 600
Mario Vernari Avatar asked Oct 23 '25 00:10

Mario Vernari


1 Answers

Index signatures apply to all members of the type that match the signature.

TypeScript does not have a way to specify "everything besides defined keys" since it does not have negated types. This pattern cannot be expressed in TypeScript today in a way that won't break. A more TS-friendly version of it puts all of the extra properties on a dedicated key:

type Foo = { a: 1; extra: { [x: string]: 2 } }
like image 182
Gerrit0 Avatar answered Oct 24 '25 15:10

Gerrit0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!