typescript 具有且仅有一个属性的对象的类型

hts6caw3  于 2023-02-20  发布在  TypeScript
关注(0)|答案(1)|浏览(140)

我想要一个对象的类型,它有且只有一个属性,具有任意键和任意类型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中可能吗?

wz8daaqr

wz8daaqr1#

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
}

相关问题