Typescript 获取 typeof 接口(interface)或类型的子字段

标签 typescript typescript-typings

给定下面声明的接口(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/

相关文章:

angular - 空合并运算符 Angular 2

typescript - webpack UMD : Critical dependency. ..无法静态解压

typescript - 创建函数类型(TypeScript 接口(interface))

typescript - 如何为 TypeScript 编译器排除 *.d.ts 文件?

node.js - 在 npm 包被删除并重命名后,如何使用旧的 typescript 类型?

typescript - 命名类型与 Typescript 的关联

typescript - 如何输入以接口(interface)作为参数的方法

reactjs - 获取trpc或react-query的useQuery结果 "data"属性的typescript类型

javascript - 为导入的组件添加样式是React

typescript - 如何在 Typescript 中编写严格要求其参数的函数类型