[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] };

 

posted @   Zhentiw  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示