我的项目中有一个主界面,用于指示扩展对象属性的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)"
如何从超级界面获得“ 强制值类型”的好处,而又没有不必要的“ 扩大键范围”?
PS。它与TypeScript: Create typed Record without explicitly defining the keys的不同之处在于,这里我要一个 interface ,而这些对象或其实例都没有开销。请停止将其重复报告。 :)
答案 0 :(得分:2)
您可以基于generic type constraint创建实用程序类型以验证输入类型的值:
# A tibble: 23 x 5
# Groups: FName [4]
FName Dispz Loadz TIMESTAMP Failflag
<chr> <dbl> <dbl> <dttm> <chr>
1 D-H1 0 0 2020-11-02 11:06:51 ""
2 D-H1 0.399 11.5 2020-11-02 11:06:52 ""
(...)
9 D-H1 2.46 49.7 2020-11-02 11:06:59 ""
10 WR-H2.2 0.409 25.3 2020-11-02 11:06:55 ""
11 WR-H2.2 0.735 35.2 2020-11-02 11:06:56 ""
12 WR-H2.2 0.942 39.5 2020-11-02 11:06:57 ""
13 WR-H2.2 1.33 51.9 2020-11-02 11:06:58 ""
14 WR-H2.2 1.34 54.7 2020-11-02 11:06:59 ""
15 WR-H2.3 1.98 41.2 2020-11-02 11:06:58 ""
16 WR-H2.3 2.05 53.8 2020-11-02 11:06:59 ""
17 WR-H2.4 0 0 2020-11-02 11:06:53 ""
18 WR-H2.4 0.244 6.64 2020-11-02 11:06:54 ""
(...)
23 WR-H2.4 0.949 43.8 2020-11-02 11:06:59 ""
答案 1 :(得分:0)
我认为至少现在不可能,因为您必须执行以下操作:
./a.out
USERNAME: someusername
PASSWORD: ********
这在递归使用interface Printable extends Record<keyof Printable, string> {
}
时给出了一个错误,对tbh没有多大意义。我想到的唯一解决方案如下。
Printable interface