我想要一个对象的类型,该对象具有一个且只有一个具有任何键和任何类型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
}
在Typescript中可以吗?
答案 0 :(得分:0)
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 obj3: ISingleKey<"property1" | "property2", boolean> = {
property1: true,
property2: true
}