给定下面声明的接口(interface)或类型,
interface Foo {
bar: {
a: number
b: string
}
}
type Foo = {
bar: {
a: number
b: string
}
}
有没有办法获取“baz”的类型定义。这样我们就可以做类似的事情
const v: keyof Foo.bar = "a";
最佳答案
是的,你可以喜欢这个
const invalid: Foo["bar"] = "a"; // Type '"a"' is not assignable to type '{ a: number; b: string; }'.(2322)
const valid: Foo["bar"] = { a: 1, b:'a' };
它适用于类型
和接口(interface)
。这是一个工作playground
关于Typescript 获取 typeof 接口(interface)或类型的子字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043101/