Typescript 如何声明描述某个对象的键和对应值类型的类型

Typescript 如何声明描述某个对象的键和对应值类型的类型,typescript,typescript-typings,Typescript,Typescript Typings,在这种情况下,如何让编译器检查值的类型 type SomeType = { foo: string[]; bar: number | null; }; type SomeTypeChanges<K extends keyof SomeType = keyof SomeType> = { key: K; value: SomeType[K] }; declare function baz(changes: SomeTypeChanges); // must be

在这种情况下,如何让编译器检查值的类型

type SomeType = {
  foo: string[];
  bar: number | null;
};

type SomeTypeChanges<K extends keyof SomeType = keyof SomeType> = {
  key: K;
  value: SomeType[K]
};

declare function baz(changes: SomeTypeChanges);

// must be an error in both cases
baz({key: "foo", value: 1}); // type of value must be string[]
baz({key: "bar", value: ["a", "b"]}) // type of value must be number | null
type SomeType={
foo:string[];
条:数字|空;
};
键入SomeTypeChanges={
关键词:K;
值:SomeType[K]
};
声明函数baz(变更:SomeTypeChanges);
//在这两种情况下都必须是错误的
baz({键:“foo”,值:1});//值的类型必须为字符串[]
baz({key:“bar”,value:[“a”,“b”]})//值的类型必须是number | null
事实上,情况更为困难 我从外部库导出这些内容:

export interface MyEvent<Payload> {
  (payload: Payload): Payload;
}
export declare function createEvent<E = void>(eventName?: string): MyEvent<E>;
导出接口MyEvent{
(有效载荷:有效载荷):有效载荷;
}
导出声明函数createEvent(eventName?:string):MyEvent;
试着使用它是这样的:

const myEvent = createEvent<SomeTypeChanges<keyof SomeType>>();
myEvent({ key: "foo", value: 1 });
                      ^^^^^
constmyevent=createEvent();
myEvent({键:“foo”,值:1});
^^^^^

因此,我无法将类型参数添加到函数中

您需要将类型参数添加到函数中。该功能是导致在调用站点发生推断的工具。仅仅因为该类型是泛型的,并不意味着会发生任何推断,而且由于将使用
K
的默认值,因此不会出现错误

这将按照您的预期工作:

type SomeType = {
  foo: string[];
  bar: number | null;
};

type SomeTypeChanges<K extends keyof SomeType> = {
  key: K;
  value: SomeType[K]
};

declare function baz<K extends keyof SomeType>(changes: SomeTypeChanges<K>);

// must be an error in both cases
baz({key: "foo", value: 1}); // err
baz({key: "bar", value: ["a", "b"]}) // err
type SomeType={
foo:string[];
条:数字|空;
};
键入SomeTypeChanges={
关键词:K;
值:SomeType[K]
};
声明函数baz(变更:SomeTypeChanges);
//在这两种情况下都必须是错误的
baz({键:“foo”,值:1});//犯错误
baz({key:“bar”,值:[“a”,“b”]})//错误

您需要将类型参数添加到函数中。该功能是导致在调用站点发生推断的工具。仅仅因为该类型是泛型的,并不意味着会发生任何推断,而且由于将使用
K
的默认值,因此不会出现错误

这将按照您的预期工作:

type SomeType = {
  foo: string[];
  bar: number | null;
};

type SomeTypeChanges<K extends keyof SomeType> = {
  key: K;
  value: SomeType[K]
};

declare function baz<K extends keyof SomeType>(changes: SomeTypeChanges<K>);

// must be an error in both cases
baz({key: "foo", value: 1}); // err
baz({key: "bar", value: ["a", "b"]}) // err
type SomeType={
foo:string[];
条:数字|空;
};
键入SomeTypeChanges={
关键词:K;
值:SomeType[K]
};
声明函数baz(变更:SomeTypeChanges);
//在这两种情况下都必须是错误的
baz({键:“foo”,值:1});//犯错误
baz({key:“bar”,值:[“a”,“b”]})//错误

@abdurahmanus我只能发布您展示的代码的解决方案,发布一个更完整的示例,我们可以看到可以是什么done@abdurahmanus我只能发布你展示的代码的解决方案,发布一个更完整的示例,我们可以看到可以做什么