有没有办法强类型输入类型为'any'的对象的属性

问题描述 投票:4回答:2

我有一个父对象,它被输入为'any',无法更改(我在单元测试中使用this对象),我正在定义父对象的属性,但无论我做什么,它总是松散地输入与'任何'。在运行时之前,施放似乎没有做任何事情。有没有办法在运行时强烈键入我的属性,所以我可以在分配伪造属性时让Typescript抛出错误?

interface AType {
    bar: number
    bas: string
}

let something: any = {};

// Make this property respect 'AType' typing.
something.anythingElse = <AType>{
 bar: 1,
 bas: 'one',
};

// Doesn't throw an Error but it should
something.anythingElse.bogusAssignment = '1234';
javascript typescript
2个回答
1
投票

在上述评论之后,除了常规类型断言之外,您可以考虑使用类型保护:

interface AType {
    bar: number
    bas: string
}

let something: any = {};

something.anythingElse = <AType>{
 bar: 1,
 bas: 'one',
};

// below type guard definition.
function isAType(arg: any): arg is AType {
    return arg && arg.anythingElse; // <-- add further type checkings here.
}

const somethingElse = something.anythingElse;
if (isAType(somethingElse)) {
    somethingElse.bogusAssignment = '1234';
                //^---- this will throw compile error and intellisense error as well.
}

在这里,bogusAssignment不起作用。

工作场所:typescript playground

编辑:对于下面的评论,这是您可以采取的另一种方法:typescript playground


0
投票

什么阻止你给父母一个更强的类型?

something: Partial<{anythingElse: AType}>
© www.soinside.com 2019 - 2024. All rights reserved.