跳到主要内容

RemoveIndexSignature

介绍

实现RemoveIndexSignature<T>, 从对象类型中排除索引签名

例如:

ts
type Foo = {
[key: string]: any
foo(): void
}
type A = RemoveIndexSignature<Foo> // expected { foo(): void }
ts
type Foo = {
[key: string]: any
foo(): void
}
type A = RemoveIndexSignature<Foo> // expected { foo(): void }
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type RemoveIndexSignature<T> = any
 
/* _____________ Test Cases _____________ */
 
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 }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<RemoveIndexSignature<Bar>, { bar(): void, 0: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<RemoveIndexSignature<FooBar>, { [foobar](): void }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<RemoveIndexSignature<Baz>, { bar(): void, baz: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type RemoveIndexSignature<T> = any
 
/* _____________ Test Cases _____________ */
 
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 }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<RemoveIndexSignature<Bar>, { bar(): void, 0: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<RemoveIndexSignature<FooBar>, { [foobar](): void }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<RemoveIndexSignature<Baz>, { bar(): void, baz: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// most popular
 
type RemoveIndexSignature<T, P=PropertyKey> = {
[K in keyof T as P extends K? never : K extends P ? K : never]: T[K]
}
 
ts
// most popular
 
type RemoveIndexSignature<T, P=PropertyKey> = {
[K in keyof T as P extends K? never : K extends P ? K : never]: T[K]
}
 
view more solutions