dee zg dee zg - 1 year ago 68
TypeScript Question

Type literals only with properties from known type

interface SomeInterface{
p1: string;
p2: number;
p3: ComplexType;
}

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


Now, is there a way to write a generic function like:

function foo<T>(parameter:T){

}


which would be called using object literal

{
...
}


but only properties that exist on
SomeInterface
would be allowed? Its important, not all properties must be in a literal call. Call could be done with:

{
p1: 'only one'
}


But call with:

{
propertyNotOnInterface: 'bla'
}


should get compiler error.

Is something like that possible?

Answer Source

You can use Partial, like so:

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

Then this is fine:

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

But this:

foo({
    propertyNotOnInterface: 'bla'
});

Results in this error:

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'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download