【问题标题】:Typescript nameof generic type T as property泛型类型 T 的打字稿名称作为属性
【发布时间】:2022-01-01 13:02:24
【问题描述】:

是否可以在类/接口中使用参数 T 的类型作为属性名?

export interface ISample<T> {
  nameof(T)      : T;  <-- this property should have the name of the type T nameof(T)
  otherProperties: any;
}

并像这样使用它:

const data: ISample<Houses>() = <something to construct the object>
console.log(data.houses)

所以houses 是由接口生成的data 的属性。

【问题讨论】:

    标签: angular typescript generics typescript-generics


    【解决方案1】:

    TypeScript 是一种结构化类型系统。也就是说,类型系统关注的是结构,而不是名称,而且类型不一定有名称,更不用说唯一的名称了。

    例如,假设你要写:

    interface Person {
      name: string;
    }
    
    interface Street {
      name: string;
    }
    

    ISample<{name: string}>
    

    应该有personstreet 属性?

    所以不,你要的东西不存在。

    您可能需要声明:

    interface PersonSample {
      person: Person;
    }
    
    interface StreetSample {
      street: Street;
    }
    

    interface Sample<T> {
      sample: T;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-27
      • 2019-03-12
      • 2021-12-30
      • 2023-01-14
      • 1970-01-01
      • 2020-10-07
      • 2021-12-06
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多