只有驼峰键的对象类型
Type of object with only camel case keys
有没有办法编写强制对象键采用驼峰式命名的类型或接口?
type CamelCaseObject = // ... ?
const myObject: CamelCaseObject;
myObject.camelCaseKey; // Ok
myObject.not_camel_case_key; // Not ok.
或者一个接口也可以。
interface ICamelCaseObject = {
[key: string /* that matches camelCase */]: OtherType;
}
const myObject: ICamelCaseObject;
myObject.camelCaseKey; // Ok
myObject.not_camel_case_key; // Not ok.
好吧,您不能使用静态类型强制字符串是驼峰式大小写。但是,您可以强制所有 属性 名称不包含下划线,这将不允许蛇形大小写:
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'.
};
有没有办法编写强制对象键采用驼峰式命名的类型或接口?
type CamelCaseObject = // ... ?
const myObject: CamelCaseObject;
myObject.camelCaseKey; // Ok
myObject.not_camel_case_key; // Not ok.
或者一个接口也可以。
interface ICamelCaseObject = {
[key: string /* that matches camelCase */]: OtherType;
}
const myObject: ICamelCaseObject;
myObject.camelCaseKey; // Ok
myObject.not_camel_case_key; // Not ok.
好吧,您不能使用静态类型强制字符串是驼峰式大小写。但是,您可以强制所有 属性 名称不包含下划线,这将不允许蛇形大小写:
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'.
};