【问题标题】:How to type a property already typed as any?如何键入已键入为 any 的属性?
【发布时间】:2022-10-31 06:24:02
【问题描述】:

我正在使用第三方库,其类型如下:

export interface ThirdPartyNodeType {
 id: string;
 name: string;
 data: any;
}

现在我知道我想在该 ThirdPartyNodeType.data 中放入什么:

export interface MyOwnDataProperties {
 foo: string;
 bar: string;
}

我怎么能告诉 TypeScript “我不希望这个 ThirdPartyNodeType.data 成为 any 了 必须是MyOwnDataProperties"的类型?

【问题讨论】:

  • 让我知道this 是否是您正在寻找的
  • 这并不是我真正想要的,因为它创建了一个新的更新界面,如果我想使用该第三方库,它将无法工作,因为它无法识别这个新界面。
  • 您可能想要创建类型定义文件*.d.ts,请参阅docs。请为我提供真实的示例第三方库的确切名称
  • 是的,它是一个类型定义,你提供的工作!
  • 您希望该更改在什么范围内生效?请edit 澄清。您希望它在任何范围内都有效吗?只是一个特定的范围?只是一个具体的说法?可以使用类型断言 (as) 更改单个语句。可以使用assertion function 更改范围。

标签: typescript typescript-typings


【解决方案1】:

如果您可以在类型周围使用包装器而不是修改类型本身,这是一种解决方法:您可以子类化接口。变通方法的一个缺点示例是,如果第三方接口是第三方代码函数的返回值的类型,并且您希望将类型更改为您的包装器类型,则需要使用类型断言 (as)。

export interface ThirdPartyNodeType {
 id: string;
 name: string;
 data: any;
}

// Instance of ThirdPartyNodeType
const a: ThirdPartyNodeType = {
    id: 'id',
    name: 'name',
    data: {}
}

// Your custom typing
export type YourData = {
    foo: string;
    bar: string;
}

// Interface inheritance
export interface ThirdPartyNodeTypeExtension extends ThirdPartyNodeType {
    data: YourData
}

// Use your custom typing
const b: ThirdPartyNodeTypeExtension = a;

// (property) ThirdPartyNodeTypeExtension.data: YourData
b.data

【讨论】:

  • 我不想创建新界面。我想重写此属性类型并保留在我的第三方库中声明的相同接口。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2018-03-07
  • 2020-07-08
  • 1970-01-01
  • 2021-12-07
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多