首页 > 解决方案 > 基于对象定义 TypeScript 类型?

问题描述

是否可以根据对象的实例定义类型?

我不想先定义接口,我想要一个将值作为输入的泛型类型,而不是类型。

例子:

const someObject: any = {
  foo: "",
  bar: ""
}

// should show error because "bar" property is missing
const someOtherObject: SameShape<someObject> {
  foo: ""
}

我现在只需要一个扁平的对象结构。所以像这样的东西(除了有效的东西):

type SameShape = { [key in keyof someObject]: string }

标签: typescript

解决方案


使用typeof运算符。

// This is valid
const someOtherObject: SameShape<typeof someObject> 

type SameShape<T> = { [key in keyof T]: string }

但是您需要先将其删除anysomeObject: any

现在对于您的用例,以下就足够了,您不需要额外的SameShape

const someOtherObject: typeof someObject = {/* ... */}

推荐阅读