Is there a way to write a type or an interface that forces the object keys to be in camelCase?
type CamelCaseObject = // ... ?
const myObject: CamelCaseObject;
myObject.camelCaseKey; // Ok
myObject.not_camel_case_key; // Not ok.
Or an interface would be fine too.
interface ICamelCaseObject = {
[key: string /* that matches camelCase */]: OtherType;
}
const myObject: ICamelCaseObject;
myObject.camelCaseKey; // Ok
myObject.not_camel_case_key; // Not ok.
Well, you can't exactly enforce that the string is camel case using static types. However, you can force all property names to not include underscores which would disallow snake case:
type OtherType = string;
interface ICamelCaseObject {
[key: string /* that matches camelCase */]: OtherType;
[K: `${string}_${string}`]: never; // matches snake case and forces never
}
// this works
const foo: ICamelCaseObject = {
heyYou: "boi",
};
// this fails
const foo2: ICamelCaseObject = {
oh_noes: "hey", // Type 'string' is not assignable to type 'never'.
};