如何为方法参数提供类型提示

时间:2018-04-30 07:11:50

标签: typescript

我正在尝试构造一个对象文字作为参数传递给方法,并希望确保它符合特定的接口。如果不首先创建该类型的临时变量,我该怎么做?

interface IPoint {
    x: number;
    y: number;
}

// A function I'm given that I can't change
function doSomething(obj: any) { }

function tryToUseDoSomethingSafely() {
    // I'm making sure that the call to doSomething takes a proper IPoint.
    // This does what I want. I'll get a compile error if I forget the x
    // or y components.
    let point: IPoint = { x: 1, y: 2 };
    doSomething(point);

    // How can I do the above WITHOUT creating the temporarily variable?
    // I want something like this where I'd get a compile error message if
    // the parameter is not a proper point; this won't compile.
    doSomething({ x: 1, y: 2 } : IPoint);
}

2 个答案:

答案 0 :(得分:0)

对于参数类型为any

,您可以传递所需的所有内容,但如果您希望属性xy具有给定参数,则可以在方法中传递,或者您可以检查是否xy是否存在可供使用,如果您的观点有时可能不在xy,则可以通过以下方式定义界面:

interface IPoint {
    x?: number;
    y?: number;
}

答案 1 :(得分:0)

我认为这里没有一个好的解决方案。我想出的最好的是构建我自己的函数exact<T>(T item) { return item; }并在我想要的任何地方使用它来确保具有保证类型的对象文字。 TypeScript设计网站上的相关问题:https://github.com/Microsoft/TypeScript/issues/7481#issuecomment-386061556

相关问题