[Typescript] 42. Medium - Remove Index Signature
Implement RemoveIndexSignature<T>
, exclude the index signature from object types.
For example:
type Foo = {
[key: string]: any;
foo(): void;
}
type A = RemoveIndexSignature<Foo> // expected { foo(): void }
Interesting, so it turns out that they represent any key on the object as a string type literal. While the index signature has just a type like number
or string
.
It leads me to the idea that we need to filter out any keys that are not type literals. But, how do we check if the type is a type literal or not? We can use the nature of sets and check if some set is a subset or not. For instance, the type literal “foo” extends from the string, but not otherwise, “foo” is too narrow to be a string.
"foo" extends string // true
string extends "foo" // false
/* _____________ Your Code Here _____________ */
type RemoveIndexSignature<T> = {
[P in keyof T as
string extends P
? never
: number extends P
? never
: symbol extends P
? never
: P]: T[P]
}
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type Foo = {
[key: string]: any
foo(): void
}
type Bar = {
[key: number]: any
bar(): void
0: string
}
const foobar = Symbol('foobar')
type FooBar = {
[key: symbol]: any
[foobar](): void
}
type Baz = {
bar(): void
baz: string
}
type cases = [
Expect<Equal<RemoveIndexSignature<Foo>, { foo(): void }>>,
Expect<Equal<RemoveIndexSignature<Bar>, { bar(): void; 0: string }>>,
Expect<Equal<RemoveIndexSignature<FooBar>, { [foobar](): void }>>,
Expect<Equal<RemoveIndexSignature<Baz>, { bar(): void; baz: string }>>,
]
type TypeLiteralOnly<T> = string extends T
? never
: number extends T
? never
: T;
type RemoveIndexSignature<T> = { [P in keyof T as TypeLiteralOnly<P>]: T[P] };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-10-05 [Typescript] Performance Bundling and tslib
2020-10-05 [Typescript] Enforcing Code Quality
2020-10-05 [Typescript] Understanding “lib” and ES libraries
2020-10-05 [Typescript] Configuration Inheritance with Extends
2018-10-05 [React] {svg, css module, sass} support in Create React App 2.0
2017-10-05 [React] Define defaultProps and PropTypes as static methods in class component
2016-10-05 [RxJS] BehaviorSubject: representing a value over time