# 2022-08
# 一、Property 'value' does not exist on type 'EventTarget'
# 二、typescript 申明值可以为空
# 背景
因为经常有定义对象初始值的时候,会附一个空值 null ,便于页面上使用的时候判断数据是否存在。存在才用 if 进行渲染,避免报错。
<section v-if="userA">
 <div>{{userA.name}}</div>
</section>
 1
2
3
2
3
interface User {
  name: string;
  contact: null | { phone: string; email: string }; // 不写 null ,定义的时候会报错。
}
const userA: User = {
  name: 'a',
  contact: null, // 初始定义为 null
};
// 模拟在其他地方设置 contact
function initContact(user: User){
  user.contact = { phone: '', email: '' };
}
initContact(userA);
// 使用 userA.contact Object is possibly 'null'
console.log(userA.contact.email)
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 解决
# 问题一:interface 里面都要写 null |,很麻烦
 定义一个工具泛型,处理可以为 null 的类型
type Nullable<T> = T | null;
interface User {
  name: string;
  contact: Nullable<{ phone: string; email: string }>;
}
type WithNullableFields<T, Fields> = {
  [K in keyof T]: K extends Fields 
    ? T[K] | null | undefined
    : T[K]
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 问题二:使用 userA.contact 的时候会报错
 暂无
# 三、git fatal: refusing to merge unrelated histories
# 背景
仓库 B 的内容是复制的仓库 A,但是没有保留之前的 commit 记录,后期想要同步仓库 A 的改动到仓库 B,merge 的时候就会报错:fatal: refusing to merge unrelated histories。
# 解决
# 方案一 -–allow-unrelated-histories
 # 添加仓库 A
git remote add <remote> url
# 合并
git checkout Bbranch
git merge <remote>/Abranch -–allow-unrelated-histories
 1
2
3
4
5
6
2
3
4
5
6