GitHub iconTwitter icon

✏️ typescript

tips about ts

import "package"

declare module "package" {
  interface types {}
}

Option 1

// global.d.ts

declare interface Window {
  log: (event: string, type: string, params: Record<string, any>) => void
}

Option 2

// global.d.ts

declare global {
  interface Window {
    global_variable: any
  }
}

export { };

无法直接定义`global.d.ts`。假设存在`package rematch`,定义了`namespace rematch`,那么可以在可以创建文件`rematch.d.ts`,通过以下方式定义全局。

declare global {
  export interface xx = {}
  namespace NodeJS {
    interface ProcessEnv {
      NODE_ENV: boolean;
    }
  }
}

export {};

At top of file, add

// @ts-nocheck
interface UserProps {
  name: string;
}

class User {
  private props: UserProps;

  get name (): string {
    return this.props.name;
  }

  private constructor (props: UserProps) {
    this.props = props;
  }

  public static create (props: UserProps) {
    return new User(props)
  }
}

refs:

  • https://khalilstemmler.com/blogs/typescript/when-to-use-a-private-constructor/

告诉编译器在编译的时候过滤`null | undefined`

type nulltype = { a: number } | undefined | null;

let nullvar: nulltype;

// always typo { a: number }
nullvar!.a;
// will be undefined
nullvar.a;

其实在隐含的表达这个属性一定会在之后初始化

  1. https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci
  2. https://stackoverflow.com/questions/50983838/what-does-mean-in-typescript/50984662

\

Sometimes we just want to highlight, but not install npm package. Like `vscode-graphql` need install `grahql-tag` to enable graphql highlight.

Another option is

const gql = String.raw

const query = gql`
  // code in here will be highlight
`
const StringIsNumber = value => isNaN(Number(value)) === false;

// Turn enum into array
function ToArray(enumme) {
    return Object.keys(enumme)
        .filter(StringIsNumber)
        .map(key => enumme[key]);
}
type index<
  T extends readonly string[],
  S,
  P extends any[] = []
> = T[P["length"]] extends S ? P["length"] : index<T, S, [...P, 1]>;

expected `index<['macos', 'windows'], 'macos'> = 0`

`String` 类型转换为 `string`

type PropConstructor<T = any> =
  | { new (...args: any[]): T & object }
  | { (): T };

type InferPropType<P> = P extends PropConstructor<infer T>
  ? unknown extends T
    ? any
    : T
  : any;

关键在于 `{ (): T }` https://github.com/type-challenges/type-challenges/issues/215