如何使用不完整的类型

How to use incomplete types

如果不创建新的接口/类型,并且不将我的类型定义中的所有字段都设为可选,我可以在不包含所有必需字段的情况下引用一个类型吗?

这是一个问题示例:

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

作为参考,Underscore 的 .findWhere 方法的类型定义是这样的:

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

我想使用 T 作为 properties 参数的类型,因为它已经有了我想要的类型信息,但尝试这样做会导致此打字稿错误:

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

是否有一些额外的语法可以让我根据需要有效地使 onetwo 字段可选?类似于以下内容:

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

我想要自动完成并在我使用错误的类型信息时提醒我(e.x。提供数字时为字符串)。

这在语言中存在吗?在这种情况下我是否必须创建一个新类型?我是否需要将所有字段设为可选?

TypeScript 中尚不存在此功能。 This is the suggestion issue tracking it.

根据跟帖Ryan Cavanaugh的分享,最新的是这个功能已经加入,会在近期的后续版本中发布(2.2.x?)。

this comment 开始看起来像这样:

// 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];
}

因此,您通过将 MyType 变为 Partial<MyType> 来使类型成为不完整类型。