是否有可能这样做取决于对这个问题的回答:
将
excludeProperties
排除属性
在运行时?
让我们先讨论答案为“否”时的解决方案。
如果
在运行时是不可变的,因为它的目的是限制
titles
,它更像是一个类型约束,而不是一个值。
类型约束与值(我自己的理解)
类型约束
:说到“
标题
不应具有“名称”和“年龄”键
['name', 'age']
.
价值
[‘姓名’、‘年龄’]
. 它存在于计算机内存中,是具体的。您可以对其进行迭代,将新元素推送到其中,甚至可以从中弹出元素。如果不需要迭代、推送或弹出,则不需要它。
interface Foo<T, E extends keyof T> {
data: T[],
titles: { [key in Exclude<keyof T, E>]: string }
}
用法:
interface Data {
id: number,
name: string,
age: number
}
let foo: Foo<Data, 'name' | 'age'>
foo = {
data: [{ id: 1, name: 'Alice', age: 20 }],
titles: {
id: 'Title for id'
}
}
foo = {
data: [{ id: 1, name: 'Alice', age: 20 }],
titles: {
id: 'Title for id',
name: 'Title for name'
// error: Type '{ id: string; name: string; }' is not assignable to type '{ id: string; }'.
}
}
const titles = {
id: 'Title for id',
name: 'Title for name'
}
foo = {
data: [{ id: 1, name: 'Alice', age: 20 }],
titles: titles
// can not catch this since "Excess Property Checks" does not work in assignments
// see: "http://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks
}
作为变量而不是类型约束(即,您需要它的具体值来进行迭代或执行其他操作),您可以将其添加回,如下所示:
interface Foo<T, E extends keyof T> {
data: T[],
titles: { [key in Exclude<keyof T, E>]: string },
excludeProperties: E[]
}
但这并不能向你保证整个过程的完备性
排除属性
let foo: Foo<Data, 'name' | 'age'> = {
data: [{ id: 1, name: 'Alice', age: 20 }],
titles: {
id: 'Title for id'
},
excludePropreties: ['name'] // is valid from the type checking perspective though 'age' is missing
}
标题
使用对象文本提供,即多余的属性检查生效,您可以检索
标题
:
const excludeProperties = Object.keys(foo.titles)
尽管如此,如果
标题
通过使用另一个变量提供。
假设我们有一个满足需求的类型。然后像这样的一个变量证实了这一点:
const foo = {
data: { id: 1, age: 2, name: 'Alice' },
titles: { id: 'ID', age: 'Age' },
excludeProperties: ['name']
}
那么如果我修改
foo.excludeProperties.push('age')
foo.titles
应改为
{ id: string }
从…起
{ id: string, age: string }
. 但是
副标题
你有价值吗
{ id: 'ID', age: 'Age' }
此外,如果你想从中获得动态特性,这个规则甚至不适用。
const foo = {
data: { id: 1, age: 2, name: 'Alice' },
titles: { id: 'ID' },
excludeProperties: ['name', 'age']
}
那么,如果我跑
foo.excludeProperties.pop()
这是不可能的
副标题
age
编译器无法知道是什么
排除属性
标题
他是那种人。
所以,为了使编译器能够确定要排除的内容,我们需要
排除属性
在编译时确定。上面展示的我的解决方案是通过泛型类型参数表达这种排除思想来实现的,泛型类型参数在编译时是确定的。
Object.freeze(['id', 'name'])
是表示编译时最终排除的另一种方式。就我所知,typescript中没有任何方法可以利用这种“确定性”。
Object.freeze
在这种情况下)。只要类型系统对对象的实际行为不可知
对象。冻结
冻结(['id','name']))
事实上,不能通过数组变量告诉编译器类型信息的本质是javascript无法用文本(Object.freeze是一个函数调用,而不是一个文本)表示不可变数组,但是编译器可以利用它。