您可以声明允许在Typescript中使用未知属性的对象文字类型吗? [英] Can you declare a object literal type that allows unknown properties in typescript?

查看:432
本文介绍了您可以声明允许在Typescript中使用未知属性的对象文字类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想确保一个对象参数包含所有必需的属性,但可以包含它想要的任何其他属性.例如:

Essentially I want to ensure that an object argument contains all of the required properties, but can contain any other properties it wants. For example:

function foo(bar: { baz: number }) : number {
    return bar.baz;
}

foo({ baz: 1, other: 2 });

但这会导致:

Object literal may only specify known properties, and 'other' does not exist in type '{ baz: number; }'.

推荐答案

好吧,我不想回答我自己的问题,但是其他答案引起了我的一点思考……这可行:

Well, i hate answering my own questions, but the other answers inspired a little thought... This works:

function foo<T extends { baz: number }>(bar: T): void {
    console.log(bar.baz);
}

foo({baz: 1, other: 2});

这篇关于您可以声明允许在Typescript中使用未知属性的对象文字类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆