![](/img/trans.png)
[英]How do you define a value of variable that will be used in two functions when a div is clicked?
[英]How do you define functions that take two object types in Typescript?
所以我已经多次遇到这个问题,我想是时候问了:
你如何定义在 Typescript 中采用两个 object 类型的函数?
我还阅读了 https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html ,并了解到现有的 union |
对于对象来说效果不佳,因为它只包含两个对象都具有的元素。
一个人为的例子
type Person = {
name: string;
age: number;
};
type Pet = {
owner: string;
};
/*
* We'd like this function to be able to take two different objects as args
*/
const randomFunction = (myObject: Person | Pet) => {
// PROBLEM:
// Property 'age' does not exist on type 'Person | Pet'.
if (typeof myObject.age !== 'undefined') console.log(myObject.age);
};
问题:属性“年龄”在“人”类型上不存在 | 宠物'。
那么你如何处理呢? 我希望能够为简单的 function 传递两种不同的 object 类型。
我正在尝试做的不是“TypeScripty”还是不推荐?
为了摆脱 TypeScript 的波浪形,我似乎需要将它分成不同的 function。
谢谢!
所以解决方案是根据@Idruskis 使用TypeGuard 。
解决方案主要写在这里: https://medium.com/ovrsea/checking-the-type-of-an-object-in-typescript-the-type-guards-24d98d9119b0
type Person = {
name: string;
age: number;
};
type Pet = {
owner: string;
};
// Typeguard
function isPerson(
data: Pet | Person,
): data is Person {
if ((data as Person).age) {
return true;
}
return false;
}
const randomFunction = (myObject: Person | Pet) => {
if (!isPerson(myObject)) return;
// No error!
if (typeof myObject.age !== 'undefined') console.log(myObject.age);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.