When working in Typescript, it appears that defining the type as shown below should create the desired outcome:
interface RecordX extends Record<string, string[]> {
id: string
}
However, an error is thrown stating:
Property 'id' of type 'string' is not assignable to string index type 'string[]'. ts(2411)
Is there a way to include a property with a different type within a Record<>
utility type?
Exploring Details and General Scenarios + Example
In general, how might one define an object with fixed properties of varying value types, alongside dynamically added properties with consistent value types?
For instance, consider the following object:
const a = {
// some properties with predefined types
id: '123',
count: 123,
set: new Set<number>(),
// and some dynamic properties
dynamicItemList: ['X', 'Y']
anotherDynamicallyAddedList: ['Y', 'Z']
} as ExtensibleRecord
Can we define a type or interface ExtensibleRecord
where:
- The types and keys of
id
,count
, andset
are fixed asstring
,number
, andSet<number>
- The types of
dynamicItemList
,anotherDynamicallyAddedList
, and any future dynamically added properties are allstring[]
I have experimented with various approaches, such as:
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[]
}
Unfortunately, each attempt results in errors.
This seems like a common and straightforward issue, but I am unable to locate an example or reference for guidance.