cocos-engine icon indicating copy to clipboard operation
cocos-engine copied to clipboard

【引擎源码】建议: 定义全局类型 Nullable 和 Nullish ,来避免大量的 | null | undefined

Open finscn opened this issue 5 months ago • 0 comments

Use Case

类型如下:

export type Nullable<T> = T | null;
export type Nullish<T> = T | null | undefined;

为什么要这么做:

目前cocos 源码中 充斥着大量的

类型 | null | undefined 
类型 | undefined | null
类型 | undefined
类型 | null
(有的地方`|`左右两侧还没有空格) 

这种混乱的顺序 和 空格的缺失, 让代码非常不易维护和阅读. 当开发者想要确定 "有哪些变量可以为空"时 , 也不是很方便, 只能用各种排列组合 或者较为复杂的正则表达式去做全文搜索.

但是 如果 使用了 Nullable / Nullish 一切都会变得优雅一些.

 // 之前的:
foo: MyClass  | null | undefined 

// 可以变为:
foo:  Nullish<MyClass> 

如果 cocos不需要严格 区分 undefined 和 null , 也可以只用一个 Nullable 同时代表 Nullable 和 Nullish

export type Nullable<T> = T | null | undefined;

以上建议希望采纳

Problem Description

.

Proposed Solution

No response

How it works

No response

Alternatives Considered

.

Additional Information

No response

finscn avatar Jun 11 '25 07:06 finscn