【发布时间】:2020-03-23 00:42:04
【问题描述】:
使用 typescript,我们可以为需要有键的对象定义一个接口,并且可以额外允许任何其他键:
interface ObjectWithTrace {
trace: string;
[index: string]: any
}
const traced: ObjectWithTrace = { trace: 'x', foo: 'bar' }; // looks good
const untraced: ObjectWithTrace = { foo: 'bar' }; // Error: Property 'trace' is missing in type '{ foo: string; }' but required in type 'ObjectWithTrace'. ts(2741)
在上面的示例中,trace 是必需的密钥。我们可以向对象添加我们想要的任何键,只要定义了trace 键,打字稿就很高兴。完美
现在,当尝试扩展此逻辑以应用于函数的参数时,会发生错误:
type FunctionWithParamWithTrace = (args: {
trace: string;
[index: string]: any
}) => any;
const doSomethingAndTrace: FunctionWithParamWithTrace = (args: { trace: string }) => {}; // looks good
const doSomethingElseAndTrace: FunctionWithParamWithTrace = (args: { trace: string, foo: 'bar' }) => {} /*
Error: Type '(args: { trace: string; foo: "bar"; }) => void' is not assignable to type 'FunctionWithParamWithTrace'.
Types of parameters 'args' and 'args' are incompatible.
Property 'foo' is missing in type '{ [index: string]: any; trace: string; }' but required in type '{ trace: string; foo: "bar"; }'.ts(2322)
*/
我好像错过了什么。有没有办法为一个函数定义一个类型,该函数期望只有 on 参数 - 并让该参数允许任何具有任何值的键,同时还需要一个键具体存在(例如,一个名为 trace 的属性)?
我希望支持的是:
const doSomethingWithTrace: FunctionWithParamWithTrace = (args: { trace: string, foo: string }) => {}; // looks good
const doSomethingWithoutTrace: FunctionWithParamWithTrace = (args: { foo: string }) => {} // Error: Property 'trace' is missing in type '{ foo: string; }'...
【问题讨论】:
标签: typescript typescript-generics