代码之家  ›  专栏  ›  技术社区  ›  Rico Kahler

如何在初始化期间断言类型符合接口?

  •  0
  • Rico Kahler  · 技术社区  · 5 年前

    我想检查我创建的对象是否符合某个接口,但我也想保持原始类型不变。

    我想要来自左手断言的intellisense,但我也希望在创建的对象仍然符合某个接口但更具体的场景中保留现有类型“未触及”(例如,没有强制转换)。

    我知道我可以通过使用 T extends 就像这样。。。

    interface Animal {
      sound: string;
    }
    
    const enforceType = <T extends Animal>(obj: T) => obj;
    
    const lossyType: Animal = {
      sound: 'bark' as const,
    };
    
    const originalType = enforceType({
      sound: 'bark' as const,
    });
    
    // note that the type of `originalType` is more than just `foo`
    const bark = originalType.sound; // type is literally `'bark'`
    const justAString = lossyType.sound; // type is just `string`
    

    playground link

    类型 originalType.sound 保持其类型,但它有点丑陋,并发出无用的JS。没有这个功能,我有没有办法实现上面的功能?

    注: 我几乎已经问过了 the same question 将近3年前,但我认为我没有正确地描述我的意图。此外,我想增加一项要求:

    任何 JS?

    0 回复  |  直到 5 年前
    推荐文章