2017-08-17 73 views
0
interface SomeInterface{ 
    p1: string; 
    p2: number; 
    p3: ComplexType; 
} 

const x :SomeInterface = { 
    p1: 'test', 
    p2: 'test', 
    p3: {//something} 
} 

现在的属性,有没有写这样的通用功能的方法:类型文字只从已知类型

function foo<T>(parameter:T){ 

} 

这将使用对象文本

{ 
... 
} 

,但只能被称为SomeInterface上存在的属性将被允许?它的重要性,并非所有的属性都必须在字面上调用。电话可以用做:

{ 
    p1: 'only one' 
} 

但与调用:

{ 
    propertyNotOnInterface: 'bla' 
} 

应该让编译器错误。

是这样的可能吗?

回答

2

您可以使用Partial,像这样:

function foo(parameter: Partial<SomeInterface>) { 
    ... 
} 

然后,这是罚款:

foo({ 
    p1: 'only one' 
}); 

但这:

foo({ 
    propertyNotOnInterface: 'bla' 
}); 

导致此错误:

Argument of type '{ propertyNotOnInterface: string; }' is not assignable to parameter of type 'Partial'.
Object literal may only specify known properties, and 'propertyNotOnInterface' does not exist in type 'Partial'.

+0

就是这样!谢谢一堆! –