When utilizing a general key with { mode: string }
type, it's important to ensure that all properties defined with a string
key type (including getMode
) also have a value type of { mode: string }
. One method to separate the getMode
from general keys is by segmenting your Obj
type into two distinct parts:
type GetModeType = {
getMode: () => string;
};
type GeneralType<T extends string> = {
[P in T as T extends "getMode" ? never : P]: { mode: string };
};
Afterwards, you can create a generic type based on their intersection:
type Obj<T extends string> = GetModeType & GeneralType<T>;
You can then proceed to create an object based on the Obj
type:
const obj: Obj<"0" | "pending"> = {
getMode: () => "hello",
["0"]: { mode: "zero" },
pending: { mode: "this is pending mode." },
};
It's worth noting that the Obj
type includes a property of getMode
with the type () => string
, and any other desired keys
should be specified as a generic type (union of string literals).
For more information on generic types and mapped types, refer to the TypeScript documentation.