Kevin Beal
Kevin Beal

Reputation: 10849

How to use incomplete types

Without creating a new interface / type, and without making all of the fields on my type definition optional, can I reference a type without including all of it's required fields?

Here's an example of the problem:

interface Test {
    one: string;
    two: string;
}
_.findWhere<Test, Test>(TestCollection, {
    one: 'name'
});

For reference, the type definition for Underscore's .findWhere method is this:

findWhere<T, U extends {}>(
        list: _.List<T>,
        properties: U): T;

I would like to use T as the type for the properties parameter since it has the type information I want already, but trying to do this results in this typescript error:

Argument of type '{ one: string; }' is not assignable to parameter of type 'Test'. Property 'two' is missing in type '{ one: string; }'.

Is there some extra syntax that will allow me to effectively make the one and two fields optional as needed? Something like the following:

_.findWhere<Test, Test?>(TestCollection, {
    one: 'name'
});

I want autocomplete and for it to alert me when I'm using the wrong type information (e.x. strings when number is provided).

Does this exist in the language? Do I have to create a new type just in this case? Am I required to make all my fields optional?

Upvotes: 5

Views: 2034

Answers (2)

Kevin Beal
Kevin Beal

Reputation: 10849

According to the thread, Ryan Cavanaugh shared, the latest is that this feature has been added and will be released in a future version in the near future (2.2.x?).

From this comment it will look like this:

// Example from initial report
interface Foo {
    simpleMember: number;
    optionalMember?: string;
    objectMember: X; // Where X is a inline object type, interface, or other object-like type 
}

// This:
var foo: Partial<Foo>;
// Is equivalent to:
var foo: {simpleMember?: number, optionalMember?: string, objectMember?: X};

// Partial<T> in that PR is defined as this:
// Make all properties in T optional
interface Partial<T> {
    [P in keyof T]?: T[P];
}

So, you make a type an incomplete type by making MyType into Partial<MyType>.

Upvotes: 2

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

This feature does not yet exist in TypeScript. This is the suggestion issue tracking it.

Upvotes: 1

Related Questions