• [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] };
  • 相关阅读:
    夺命雷公狗---ECSHOP---08---商品页的拇改成星星
    夺命雷公狗---ECSHOP---07---商品价格的遍历
    夺命雷公狗---ECSHOP---06---商品倒计时的实现
    WordPress博客密码忘记的解决方法
    夺命雷公狗---js_mv思路
    LAMP前一定要关闭防火墙
    夺命雷公狗---Smarty NO:25 缓存控制技术2(完结)
    夺命雷公狗---Smarty NO:24 缓存控制技术1
    夺命雷公狗---Smarty NO:23 常用方法
    夺命雷公狗---Smarty NO:22 常量—变量
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16754928.html
Copyright © 2020-2023  润新知