我有以下代碼:如何告訴TypeScript對象中的可選屬性是否存在並被設置?
interface First
{
propertyA: string;
}
// Here propertyA is optional
// Imagine that this interface came from external library.
interface Second
{
propertyA ?: string;
}
function fn(arg: First)
{
// ...
}
// I know that this object can be declared as type of First,
// but I really need set this as type of Second interface
let myVar: Second = {propertyA: 'some string'};
// I really need in this way to make the call.
fn(myVar); // Error
if(myVar.hasOwnProperty('propertyA'))
{
fn(myVar); // Still same error
}
if(myVar.propertyA)
{
fn(myVar); // Still same error
}
但打字稿扔錯誤:
Argument of type 'Second' is not assignable to parameter of type 'First'. Property 'propertyA' is optional in type 'Second' but required in type 'First'.
那麼,如何告訴在myVar
可選屬性propertyA
存在並設置打字稿?
如果你認真對待我的問題,那麼也許它會更容易理解。例如,如果我使用外部庫,我不能更改'interface Second'的定義,但它仍然與'interface First'兼容。 – ktretyak
問題是由於可選屬性,接口'Second'與接口'First'不兼容。無論如何,我提出的所有3種解決方案都適用於這種情況。 –