好 继续来笔记 Narrowing, 还有哪些方法能进行 narrow 型别呢。 若有错误,欢迎留言指教,感恩的心。
parameterName is Type
。以下方例子, pet is Fish
就是 type predicate。parameterName
必须要是函式中参数的名称,下方例子的的参数名称就是 pet
, 所以 parameterName
就会是 pet
。type Fish = { swim: () => void };
type Bird = { fly: () => void };
//pet 有可能是 Fish or Bird 的型别
//isFish 这个function 回传值的型别为 : pet is Fish,看是回传 true or false
//当返回了true, 那他就是Fish
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined; //(pet as Fish)断言 pet 为 Fish 型别 , 所以 swim 不会是undefined
}
TypeScript 可以针对相同的可识别的属性来自动判断型别,再去执行不同情境的操作,他有3个要素:
kind
type Shape = Circle | Square;
shape.kind === "circle"
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
}
let area = getArea({ kind: "circle", radius: 5});
console.log(area);
看 pj 大大的文章是推荐在接收後端传来的 response 的时候很好用, status 是 OK 的话,则资料会带有 payload,否则资料会带有 error。我们可以自行定义多个不同的 Type,这些Type有共同的栏位, 如 status
,那就用这个栏位来判断还有哪些属性。
最後没有判断到的情况可以利用 exhaustiveness checking, 用never
型别表示不应该存在的状态,一般用於错误处理。
interface ISuccessResp {
status: 'OK'; //相同栏位 status
payload: unknown;
}
interface IErrorResp {
status: 'ERROR';
errorCode: number;
description: string;
}
type Resp = ISuccessResp | IErrorResp;
const parseResponse = (resp: Resp) => {
switch (resp.status) {
case 'OK': //透过 narrow 知道是 ISuccessResp 型别
return resp.payload; //则去使用ISuccessResp的属性payload
case 'ERROR': // 透过 narrow 知道是 IErrorResp 型别
return resp.description; //则去使用IErrorResp的属性payload
default:
const _exhaustiveCheck: never = resp;
return _exhaustiveCheck;
}
};
这两天跑出去玩,帮好久不见的朋友庆生,久违的开心XD (好多好朋友都是10月生日, 生日快乐呀, 天秤宝宝们
不过回到家,看到文章库存一天一天用完,觉得好可怕 QQ,然後明天又是礼拜一了,一起加油!!
https://pjchender.dev/typescript/ts-narrowing/#user-defined-type-guards
https://www.typescriptlang.org/docs/handbook/2/narrowing.html
https://ithelp.ithome.com.tw/articles/10222470
https://blog.csdn.net/weixin_34088583/article/details/92693893
https://zh.wikipedia.org/wiki/%E6%A0%87%E7%AD%BE%E8%81%94%E5%90%88
今天来处理昨天建立的 Category 商品类别模型 假如说商店有机会扩大经营的话,那商品类别势必会...
今天一样是 ISO 硬硬的标准,第七节 资源 及 传达。 通常分切成【人力资源安全】及【文件化资讯】...
除了 Tailwind CSS - 设定自己想要的 TailwindCSS 样式 Variant ...
今天学习进度还是 鸟哥的 Linux 私房菜 -- DNS Server /etc/nsswitch...
Utilize Mbed API to implement interrupts Purpose o...