![](/img/trans.png)
[英]How to pass a function as an argument to a ReactJS component in TypeScript
[英]How to pass an argument with multiple types as an argument to a function in Typescript?
打字稿新手在這里。
React 中的組件接收特定類型的 prop。 這個道具然后被進一步用來做一堆其他的東西。
組件:
const ComponentA : SomeComponent<{
dateVal?: string
}> = ({
dateVal
}) => {....}
dateVal
是一個string
因為已經有一些代碼要求它是這種方式。 我現在想使用現有的輔助函數並將dateVal
作為參數傳遞。
輔助功能:
export const helperFunction = (param1?: Param1, date?: Date): string | null => {...}
我如何使用helperFunction
因為參數需要是Date
類型? 我試着像這樣調用它helperFunction(param1, new Date(dateVal))
但我得到了錯誤Argument of type 'string | undefined' is not assignable to parameter of type 'string | number'.
Argument of type 'string | undefined' is not assignable to parameter of type 'string | number'.
解決這個問題的最佳方法是什么? 在 Typescript 中有沒有辦法通過顯式定義其類型來傳遞參數? 或者我可以添加一些條件邏輯來傳遞參數嗎?
問題是new Date(dateVal)
構造函數期望dateVal
是字符串或數字。 您正在傳遞string | undefined
類型的dateVal
string | undefined
string | undefined
,因為它是可選的。
如果您 100% 確定dateVal
是一個字符串,您可以使用感嘆號告訴 TypeScript “我確定這不是undefined
或null
”,如下所示:
helperFunction(param1, new Date(dateVal!))
當然,通常你會使用類型保護,TypeScript 會意識到dateVal
必須是一個字符串,例如:
if (!dateVal) {
// We know dateVal is undefined or the empty string
return; // return something
}
// TypeScript now knows that dateVal has to be a string
// otherwise the if-statement would've returned earlier
helperFunction(param1, new Date(dateVal))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.