【发布时间】:2021-02-01 12:34:44
【问题描述】:
我的问题是是否可以使用 typeof 来推断 const 变量的实际类型,而不依赖于定义的更广泛的类型?
如果您假设嵌套对象看起来像一棵树并且简单属性是叶子。然后我想有一种方法来定义子树。
我想在使用in keyof 的泛型中使用它,并且只想迭代明确提到的键,而不是类型定义的所有隐含键。在下面的示例中,我需要 keyof typeof a 不包括 bar 或 baz。
示例
这个想法是Base 类型旨在定义变量a 的“最大扩展”的可能结构,并允许在编写a 时使用自动补全。
一旦a 被定义,它就有自己的更窄的类型,我想稍后用它来过滤某些键。
type Base = {
foo?: string;
bar?: string;
baz?: string;
}
const a: Base = {
foo: '123',
};
const a_typeof: typeof a = {
foo: '123',
bar: '123', // I want this to be wrong
};
我知道,由于我将 a 定义为 Base 类型,因此它们等于 type of a == Base,但我希望 typeof a = { foo: string } 和 { foo: string } 是更窄的 Base 类型。
特别是,如果我从a 的定义中删除: Base,我会得到想要的效果。
const b = {
foo: '123',
};
const b_typeof: typeof b = {
foo: '123',
bar: '123',
// ^: Type '{ foo: string; bar: string; }' is not assignable to type '{ foo: string; }'
};
【问题讨论】:
-
Typescript 是 structurally typed 语言。所以,只要
a_typeof包含a的所有mandaory 元素,它就不会关心它有什么额外的元素。它会认为它是一个有效的typeof a -
我编辑了描述。在
keyof typeof a中,我只需要遍历真正编写的属性(此处为foo),而不是在Base中遍历所有属性。 -
为什么不能在你的案例中使用第二个例子?
-
我想使用自动补全,当我写
a时,这很好用,当我使用: Base时。
标签: typescript typescript-typings typescript-generics