In Typescript the following seems like it should accomplish the creation of the desired type:
interface RecordX extends Record<string, string[]> {
id: string
}
but this complains about:
Property 'id' of type 'string' is not assignable to string index type 'string[]'. ts(2411)
How can one add a property of a different type to a Record<> utility type?
Details and General Case + Sample
Generally, how can one describe an object with heterogenous-value-type fixed properties but homogenous-value-type properties that are dynamically added.
S, for example given this object:
const a = {
// some properties with known "hard-coded" types
id: '123',
count: 123,
set: new Set<number>(),
// and some dynamic properties
dynamicItemList: ['X', 'Y']
anotherDynamicallyAddedList: ['Y', 'Z']
} as ExtensibleRecord
So how can one define a type or interface ExtensibleRecord where:
- the types and property keys of
id,count, andsetare fixed asstring,numberandSet<number> - the types of
dynamicItemListandanotherDynamicallyAddedListand any other properties added to the object arestring[]
I've tried many variants that I'd think might work, including:
type ExtensibleRecord = {
id: string, count: number, set: Set<number>
} & Record<string, string[]>
type ExtensibleRecord = {
id: string, count: number, set: Set<Number>
} & Omit<Record<string, string[]>, 'id'|'count'|'set'>
interface ExtensibleRecord = {
id: string,
count: number,
set: Set<number>,
[k: string]: string[]
}
but each seems to result in errors.
This feels like something common and obvious, but I can't find an example or reference.
Record<string, string[]>means that theidproperty, if it exists, must be astring[]. You can't extend it with something that doesn't match that; you're trying to make an exception, not an extension, and TypeScript does not (yet) support that as a concrete type. You might want to expand on your use case if you'd like a suggestion for what to do instead. And please make sure your code is a minimal reproducible example; right now a name collision withRecordis obscuring your issue.satisfieskeyword can help here.