Wuxh

Front-end Development

0%

TS的一些特殊示例 (持续更新)

该文章记录一些平时工作中一些特殊场景类型推导, 归纳总结一下。

定义一个不包括某些 Key 的对象

1
2
3
4
5
6
7
8
9
10
interface Options {
name: string;
age?: number;
}

type Valid = Record<string, any> & Partial<Record<keyof Options, never>>;

const foo: Valid = { name: 'foo' }; // error
const bar: Valid = { age: 1 }; // error
const baz: Valid = { other: 'baz' }; // okay

为 Object.defineProperty 添加类型推导

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
type InferValue<Prop extends PropertyKey, Desc> = Desc extends { get(): any; value: any }
? never
: Desc extends { value: infer T }
? Record<Prop, T>
: Desc extends { get(): infer T }
? Record<Prop, T>
: never;

type DefineProperty<Prop extends PropertyKey, Desc extends PropertyDescriptor> = Desc extends {
writable: any;
set(val: any): any;
}
? never
: Desc extends { writable: any; get(): any }
? never
: Desc extends { writable: false }
? Readonly<InferValue<Prop, Desc>>
: Desc extends { writable: true }
? InferValue<Prop, Desc>
: Readonly<InferValue<Prop, Desc>>;

function defineProperty<
Obj extends object,
Key extends PropertyKey,
PDesc extends PropertyDescriptor
>(obj: Obj, prop: Key, val: PDesc): asserts obj is Obj & DefineProperty<Key, PDesc> {
Object.defineProperty(obj, prop, val);
}

const storage = {
currentValue: 0
};

defineProperty(storage, 'maxValue', {
value: 9001,
writable: false
});

storage.maxValue = 100; // error

欢迎关注我的其它发布渠道