我试图通过滥用打字稿来强制执行自定义类型规则。 我已经开始使用它了,但是我在接口上遇到了麻烦。 这是有效的类版本:
export class HeaderElement extends WebElement {
// 'dummy' type: won't create any instances of it at runtime.
// type-filler member that doesn't exist in other WebElement.
_HEADER_ELEMENT_TYPE_FILLER_6897689FSAFDSF: string;
// -> dummy member: not even read/written/set in code.
}
const export function getHeaderElement(): HeaderElement {
// findElement: returns WebElement type
const header = browser.findElement( ... );
return header as HeaderElement;
// **tricking typescript (actual runtime type would be 'WebElement')**
}
export function clickWowPageMenu(
headerElem: HeaderElement
// (headerElem's runtime-type is WebElement.
// It's 'HeaderElem' only in compilation phase.)
) { ... }
const headerElem = getHeaderElement();
const saveButtonElem = getSaveButtonElement();
clickWowPageMenu( headerElem ); // ok
clickWowPageMenu( saveButtonElem ); // type-error.
但是对于interfaces版本,以下代码会导致typescript类型错误:
interface IContext {
__EXTENDS_IContextElem123124: string,
}
interface IChatContext extends IContext {
name: string,
}
const test: IChatContext = { name: 'namehere' } as IChatContext;
// want: no type error here. (but 'missing __EXTENDS_IContextElem123124')
const test2: IChatContext = {} as IChatContext;
// want: type error here. (missing property 'name')
我如何滥用'打字机类型检查接口我想要的方式?还是有其他方式(例如官方的东西)?
谢谢!
---------------- EDITS --------- 抱歉打字错误
const test: IContextElem ... --> IContext
答案 0 :(得分:1)
TypeError是正确的,因为您有// URL scheme: http://gist.github.com/*
// API endpoint: http://gist.github.com/services/oembed/
// Example call: http://gist.github.com/services/oembed/?url=http%3A//gist.github.com/54099
而不是IContextElem
。
更改后,您的示例会在playground
中再次编译