![](/img/trans.png)
[英]How to check the type of a parameter passed to a function in JavaScript?
[英]How to check if a parameter passed is the type of my interface
我有一個 function 需要一個 object 現在這個對象的形狀可以是三個接口之一:
interface A{
strig:string
}
interface B{
number:number
}
interface C{
boolean:boolean
}
function 需要這個 object 並根據 object 的形狀做不同的事情我想做這樣的事情
function doSomething(item: object){
if(item typeof A) do A effecst;
if(item typeof B) do B effect;
if(item typeof B) do C effect;
}
但是我收到錯誤消息“'IComic' 僅指代一個類型,但在這里它被用作一個值。”
讓我們首先嘗試僅針對 A。 我們這里有界面:
interface A {
string: string;
}
現在要檢查它,我們必須使用類似於typeof value.string === "string"
的東西。 讓我們從 function 返回:
function isA(value: any) {
// check if value is truthy first
return value && typeof value.string === "string";
}
然后我們只使用類型謂詞:
function isA(value: any): value is A {
您現在可以使用它來縮小 if 語句(或任何條件)中的值:
if (isA(aOrBOrC)) {
aOrBOrC // is now type A
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.