TypeScript:从Record <>接口继承值的类型,而不是所有键 问题

问题描述

我的项目中有一个主界面,用于指示扩展对象属性的value类型。

为简单起见,让我们假设它是这样的:

interface Printable extends Record<PropertyKey,string> {
}

这只是说所有value应该是string。并且它正确禁止其扩展接口具有number键,如下所示。

interface Receipt extends Printable {
    customerName: string;
    // customerId: number;  // EXPECTED: This line errors if uncommented (Property 'customerId' of type 'number' is not assignable to string index type 'string'. (2411))
}

但是,不必要的副作用是它将“键”的范围扩大为“任何string”,因此它不会捕获以下错误:

const r: Receipt = { customerName: "Jack" };
console.log(r.address); // UNEXPECTED: This line DOESN'T error "for Property 'address' does not exist on type 'Receipt'.(2339)"

Typescript Playground Link

问题

如何从超级界面获得“ 强制值类型”的好处,而又没有不必要的“ 扩大键范围”?


PS。它与TypeScript: Create typed Record without explicitly defining the keys的不同之处在于,这里我要一个 interface ,而这些对象或其实例都没有开销。请停止将其重复报告。 :)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)