具有泛型属性的对象的Typescript对象

k7fdbhmy  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(153)

是否可以使嵌套对象属性具有泛型类型?
大概是这样的

type func = <P extends any>(props: P) => ...
type Obj = {
   [key: string]: {f: func, args: PARAMETERS OF "f"}
}
const demo: Obj = {
   // here the type of "args" should be {name: string, age: number}
   key1: {f: (props: {name: string, age: number}) => ..., args: HERE SHOULD BE TYPED},  

   // here the type of "args" should be {somethingRandom: number[]}
   key2: {f: (props: {somethingRandom: number[]}) => ..., args: HERE SHOULD BE TYPED},

   ... more properties
}
zu0ti5jz

zu0ti5jz1#

您可能正在搜索satisfies

const demo = {...} satisfies Obj;

打印稿文档:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator
(note您需要TypeScript 4.9+来完成此操作)

相关问题