我想要一种对象类型,该类型具有且仅有一个具有任何键和任何类型 T 的属性。
type ObjWithOneProperty<T> // = ?
// OK
const obj1: ObjWithOneProperty<boolean> = {
property1: true
}
// OK
const obj2: ObjWithOneProperty<boolean> = {
property2: true
}
// OK (I know tsc wont check this, but it's what I want to express)
const f = (key: string): ObjWithOneProperty<boolean> => {
let obj = {}
obj[key] = true
return obj
}
// Type error
const obj2: ObjWithOneProperty<boolean> = {}
// Type error
const obj3: ObjWithOneProperty<boolean> = {
property1: true,
property2: true
}
这在打字稿中可能吗?
interface IPropertyOne<T> {
property1: T;
}
// OK
const obj1: IPropertyOne<boolean> = {
property1: true
}
// Type error
const obj2: IPropertyOne = {}
// Type error
const obj3: IPropertyOne<boolean> = {
property1: true,
property2: true
}
这是静态密钥版本,您想要动态密钥吗?
编辑:动态密钥版本
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void)
? I
: never;
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
type ISingleKey<K extends string, T> = IsUnion<K> extends true ? "Can only contain a single key" : Record<K, T>;
// OK
const obj1: ISingleKey<"property1", boolean> = {
property1: true
}
// Type error
const obj2: ISingleKey<"property1", boolean> = {}
// Type error
const obj3: ISingleKey<"property1", boolean> = {
property1: true,
property2: true
}
// Type error 2 keys.
const obj4: ISingleKey<"property1" | "property2", boolean> = {
property1: true,
property2: true
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)