✏️ typescript
tips about ts
type Filter<T> = {
[K in keyof T]: {
fieldName: K;
operator: "like" | "equal" | "notLike" | "notEqual";
value: T[K];
};
}[keyof T];
PS: 这段代码的写法的确比较十分新奇
it will looks like
const model = {
stringProp: "str",
hamburgerProp: 123,
booleanProp: true
};
type FilterForModel = Filter<typeof model>;
/* type FilterForModel = {
fieldName: "stringProp";
operator: "like" | "equal" | "notLike" | "notEqual";
value: string;
} | {
fieldName: "hamburgerProp";
operator: "like" | "equal" | "notLike" | "notEqual";
value: number;
} | {
fieldName: "booleanProp";
operator: "like" | "equal" | "notLike" | "notEqual";
value: boolean;
} */
refs: https://github.com/microsoft/TypeScript/issues/36444
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 {};
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;
其实在隐含的表达这个属性一定会在之后初始化
- https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci
- 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`