TypeScript-Lookup Types - Cannot access ‘xxx‘ because ‘xxx‘ is a type, but not a namespac

news/2025/2/26 19:51:59

如果我想希望使用某种类型声明的子类型作为某个变量声明的类型…

typescript">export interface Car {
    Name: string;
    Speed: number;
    Manufactured: number;
}

const Speed: Car.Speed = 200;

上面的写法会抛出错误

Cannot access ‘Car.Speed’ because ‘Car’ is a type, but not a namespace. Did you mean to retrieve the type of the property ‘Speed’ in ‘Car’ with ‘Car[“Speed”]’

这是因为你的使用姿势不对。需要用如下的写法

typescript">const Speed: Car['Speed'] = 200;

这种类型称为Lookup Types

这种使用某种类型的"成员类型"作为类型声明的使用有两种方式:

typescript">interface Person {
  name: string;
  age: number;
  location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person }; // string

或者

typescript">type P1 = Person["name"]; // string
type P2 = Person["name" | "age"]; // string | number
type P3 = string["charAt"]; // (pos: number) => string
type P4 = string[]["push"]; // (...items: string[]) => number
type P5 = string[][0]; // string

参考:

https://stackoverflow.com/questions/55607608/how-can-i-reuse-a-type-of-an-interface-member


http://www.niftyadmin.cn/n/1382680.html

相关文章

玩转Go语言之结构体

结构体//定义结构体类型 type Person struct {name stringage intheight float64 }//定义结构体变量 var student Person//给结构体属性赋值 student.name "zhangsan" student.age 20 student.height 170.0//打印结构体 Println(student)复制代码总结:1.Go语言中的…

[na]二层+tcp/udp数据包格式

标准:6623 17 3 思科:6623320 6 ip首部格式 tcp首部格式 转载于:https://www.cnblogs.com/iiiiher/p/5480947.html

AWS发布Lambda@Edge,支持在CloudFront CND的边缘服务器上执行Node.js函数

Amazon Web服务(AWS)发布了LambdaEdge,让客户可以在全球的AWS站点运行Node.js Lambda函数,从而以非常低的延迟动态地响应最终用户。\\开发者可以用LambdaEdge将Node.js代码上传到AWS Lambda——Amazon的“serverless”服务&#x…

图文讲解flexbox 布局 以及几个高频度属性的深度剖析。

文章目录display: flexflex-directionflex-growflex-shrinkalign-itemsjustify-contentflex布局中,涉及到的CSS属性以及对应的值还是非常多的。但实际应用中,其实只要掌握几个重要的核心属性就可以应付95%以上的场景了。这些属性如下:display…

android中handler用法总结

一、Handler的定义: Handler主要接收子线程发送的数据, 并用此数据配合主线程更新UI,用来跟UI主线程交互用。比如可以用handler发送一个message,然后在handler的线程中来接收、处理该消息,以避免直接在UI主线程中处理事务导致影响UI主线程的其…

限制Activity Instance实例的数量

2019独角兽企业重金招聘Python工程师标准>>> StrictMode里面有一个Activity 实例个数限制检测,当时这个只会是在开发的时候开启,而且这个没有任何回调,不能处理一些自己的逻辑,翻了一下源码,是在ActivityTh…

7-Data Recovery Suite(数据恢复套装) v4.2中文免费版

软件大小:2.9M更新日期:2018/3/12软件语言:多国语言[中文]软件类别:数据恢复软件授权:免费软件软件官网:适用平台:WinAll7-Data Recovery Suite是一款多功能一体化数据恢复软件,界面…

前端单网页应用history下配置nginx路由

单网页应用中,页面只有一个index.html的入口文件。如果使用history模式,对于不同的url我们希望最终都可以访问到index.html。 一般公司都会使用nginx作为其对外的服务器。在vue-router的官网上,实际上已经写出了如何配置: locat…