2017-05-23 53 views
0

我有一个config.js文件:如何检查实例成员类型是否与TypeScript中的实例接口相同?

window.cb_c07d1fb54766d45482d({ 
    "descriptionMaxLength": 100 
}); 

我加载这种方式:

interface TemplateData { 
    descriptionMaxLength: number; 
} 

private getTemplateData(): Promise<TemplateData> { 
    return new Promise<TemplateData>((resolve, reject) => { 
     (window as any)[cb_c07d1fb54766d45482d] = (data: any) => { // the callback func is hardcoded here in order to simplify the reading 
      resolve(data); // implicit cast 
     }; 

     scriptInclude(url); 
    }); 
} 

此代码的伟大工程,但如果让我配置了一个错误,它不会打破:

window.cb_c07d1fb54766d45482d({ 
    "descriptionMaxLength": "break my code", // mistake 
}); 

这里,descriptionMaxLength加载的将是一个字符串,即使它在接口中被描述为一个数字。

所以,以确保配置文件是有效的,我可以这样做:

private checkType(data: TemplateData): boolean { 
    return typeof data.descriptionMaxLength === "number"; 
} 

但我看到两个问题这样做:

  1. 这是很多枯燥的工作,如果我的配置文件很重(如200行)
  2. 如果我决定改变一个类型,但是我忘记在这个 方法中改变它,我引入了一个错误。

所以我想知道在Typescript中是否有一个泛型方法来确保对象的成员具有与它实现的接口相同的类型?

谢谢你的帮助!

+0

你在哪里将你的配置链接到主文件?他们如何连接? – Aron

+0

@Aron在诺言块内,在“return new Promise”行后面 –

+0

问题在于TypeScript不知道'(window as any)[callbackFunc]'在运行时会是什么样的。你不能在编译时导入配置文件吗? – Aron

回答

0

我认为你可以尝试强制tsc/IDE检查配置文件而不是你的有效性。声明你的设置结构沿着实际设置在config.ts文件是这样的:

export interface ISettings 
{ 
    descriptionMaxLength: number; 
} 

export const Settings: ISettings = 
{ 
    descriptionMaxLength : 123, 
}; 

然后后面的代码输入他们像这样:

import {Settings} from './config'; 

如果您由于某种原因不使用模块,你仍然可以只要使用类似的方法,config.ts将成为你项目的一部分并得到编译。只要有人犯了错误 - 你的构建将被破坏,IDE也会投诉。

0

您可以使用TypeScript功能Declaration Merging以在Window中声明额外的对象。

interface Window { 
    cb_c07d1fb54766d45482d: (config: { 
     descriptionMaxLength: number 
    }) => any; 
} 
interface TemplateData { 
    descriptionMaxLength: number; 
} 

window.cb_c07d1fb54766d45482d({ 
    descriptionMaxLength: 100 
}); 

function getTemplateData(): Promise<TemplateData> { 
    return new Promise<TemplateData>((resolve, reject) => { 
     window.cb_c07d1fb54766d45482d = (data: any) => { 
      resolve(data); 
     }; 
    }); 
} 

我认为像这个例子的东西会为你工作。

相关问题