Typescript 类型任意数量的通用字段

Bal*_*des 6 typescript

首先,我不能 100% 确定我想做的事情是否可能,但我尝试描述最好的可能。

interface Property<T> {
  value: T
}

interface PropertyBag {
  [key: string]: Property<???>
}

function toPlainObject(props: PropertyBag): ??? {
  return Object.keys(props)
    .reduce((acc, key) => Object.assign(acc, { [key]: props[key].value }), {})
}
Run Code Online (Sandbox Code Playgroud)

一个演示我想做的事情的例子:

interface Person {
  name: string
  age: number
}

const name: Property<string> = { value: 'John Doe' }
const age: Property<number> = { value: 35 }

const props: PropertyBag = { name, age }

const person: Person = toPlainObject(props)
Run Code Online (Sandbox Code Playgroud)

我想知道的是我怎样才能输入toPlainObjectand 的返回类型PropertyBag(其中类型是???)。使用 TS 是否可以实现这一点?

Tit*_*mir 4

如果添加额外的泛型参数PropertyBag并使用映射类型,则可以执行与此类似的操作:

interface Property<T> {value: T }
type PropertyBag<T> = { [P in keyof T]: Property<T[P]> }
Run Code Online (Sandbox Code Playgroud)

基本上T将作为属性包的属性名称和属性类型的持有者。您可以像这样显式定义一个实例:

const name: Property<string> = { value: 'John Doe' }
const age: Property<number> = { value: 0 }
let bag : PropertyBag<{ name : string, age: number}> = { age, name };

interface Person { name : string, age: number}
let personBag : PropertyBag<Person > = { age, name };
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个有助于处理类型的函数,这样您就不必手动指定所有属性和类型

function createBag<T>(props: PropertyBag<T>):PropertyBag<T> {
    return props;
}


const name: Property<string> = { value: 'John Doe' }
const age: Property<number> = { value: 0 }
let bag  = createBag({ age, name }); // infered as PropertyBag<{age: number;name: string;}>
Run Code Online (Sandbox Code Playgroud)

您当然可以将其用于您的功能:

function toPlainObject<T>(props: PropertyBag<T>): T {
    return (Object.keys(props) as Array<keyof T>)
        .reduce((acc, key) => Object.assign(acc, { [key]: props[key].value }), {}) as any;
}

const name: Property<string> = { value: 'John Doe' }
const age: Property<number> = { value: 0 }

const person:Person  = toPlainObject({ name, age })
Run Code Online (Sandbox Code Playgroud)