我对TypeScript感到非常兴奋,所以我开始玩它.作为一个Actionscript开发人员,它使Javascript变得不那么难了.
但是,在Actionscript中,可以使用is运算符在运行时检查类型:
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject);// true
trace(mySprite is IEventDispatcher); // true
Run Code Online (Sandbox Code Playgroud)
是否可以检测变量(extends或)是否是TypeScript的某个类或接口?我在语言规范中找不到任何关于它的东西,在使用类/接口时它应该存在.
有没有办法在TypeScript语言中进行方法重载?
我希望实现这样的目标:
class TestClass {
someMethod(stringParameter: string): void {
alert("Variant #1: stringParameter = " + stringParameter);
}
someMethod(numberParameter: number, stringParameter: string): void {
alert("Variant #2: numberParameter = " + numberParameter + ", stringParameter = " + stringParameter);
}
}
var testClass = new TestClass();
testClass.someMethod("string for v#1");
testClass.someMethod(12345, "string for v#2");
Run Code Online (Sandbox Code Playgroud)
这是我不想做的一个例子(我真的很讨厌在JS中重载hack的那部分):
class TestClass {
private someMethod_Overload_string(stringParameter: string): void {
// A lot of code could be here... I don't want to mix it with switch or if statement in …Run Code Online (Sandbox Code Playgroud) 有没有办法在Typescript中将字符串解析为JSON.
示例:在JS中,我们可以使用JSON.parse().在Typescript中有类似的功能吗?
我有一个JSON对象字符串,如下所示:
'{"name":"Bob","error":false}'
我写了这段代码
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是TypeScript给了我这个错误:
'Foo' only refers to a type, but is being used as a value here.
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我认为instanceof可以检查我的值是否具有给定类型,但TypeScript似乎不喜欢这样.
我在运行时加载JSON配置文件,并使用接口来定义其预期结构:
interface EngineConfig {
pathplanner?: PathPlannerConfig;
debug?: DebugConfig;
...
}
interface PathPlannerConfig {
nbMaxIter?: number;
nbIterPerChunk?: number;
heuristic?: string;
}
interface DebugConfig {
logLevel?: number;
}
...
Run Code Online (Sandbox Code Playgroud)
这样可以方便地访问各种属性,因为我可以使用自动填充等.
问题:有没有办法使用此声明来检查我加载的文件的正确性?即我没有意外的属性?
在Typescript接口和类之间有什么不同?我什么时候使用Class?我什么时候使用Interfaces?他们有什么好处?
我需要为我的后端服务器(使用Angular 2执行它)创建某种类型的http请求,例如:},
"fields": {
"project": {
"id": "10000"
},
"summary": "something's wrong",
"issuetype": {
"id": "10000"
},
"assignee": { // not neccesary required
"name": "homer"
},
"reporter": {
"name": "smithers"
},
"priority": { // not neccesary required
"id": "20000"
}
}
Run Code Online (Sandbox Code Playgroud)
我应该用什么来构建这些模型?谢谢!
我在Typescript中使用一个接口来定义一个仅在扩展基类的某些类上可用的函数.这是我到目前为止的代码的简化版本:
class Animal {
}
interface IWalkingAnimal {
walk(): void;
}
class Dog extends Animal implements IWalkingAnimal {
}
class Cat extends Animal implements IWalkingAnimal {
}
class Snake extends Animal {
}
private moveAnimal(animal: Animal) {
if (animal instanceof Cat || animal instanceof Dog) {
animal.walk();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,问题是我将添加更多"行走"动物,因此moveAnimal功能将变得太大而无法管理.我想做的是这样的事情:
private moveAnimal(animal: Animal) {
if (animal implements IWalkingAnimal ) {
animal.walk();
}
}
Run Code Online (Sandbox Code Playgroud)
但是'implements'检查不起作用,我在使用接口时找不到'instanceof'的等价物.在Java中,似乎使用'instanceof'可以在这里工作,但TypeScript不允许这样做.
TypeScript中是否存在这样的东西,或者这里有更好的方法吗?我使用的是TypeScript 1.8.9.
给出以下代码:
module MyModule {
export interface IMyInterface {}
export interface IMyInterfaceA extends IMyInterface {}
export interface IMyInterfaceB extends IMyInterface {}
function(my: IMyInterface): void {
if (my instanceof IMyInterfaceA) {
// do something cool
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误"找不到名字IMyInterfaceA".处理这种情况的正确方法是什么?
我想为我的类定义一个接口,其中包含一个isValidConfig用作类型保护的函数。但我不知道如何声明。
我已经这样做了:
type AnyConfig = ConfigA | ConfigB | ConfigC;
public abstract isValidConfig<T extends AnyConfig>(config: AnyConfig): config is T;
Run Code Online (Sandbox Code Playgroud)
和
public abstract isValidConfig<T = AnyConfig>(config: T): config is T;
Run Code Online (Sandbox Code Playgroud)
但我在实现中总是遇到错误,例如:
public isValidConfig<T extends ConfigA >(config: T): config is T {
return config.type === TrainingTypes.A;
} /// Types of parameters 'config' and 'config' are incompatible.
Type 'T' is not assignable to type 'ConfigA '.
Run Code Online (Sandbox Code Playgroud)
是否有可能做到这一点?我还没有找到路。
我有一个应用程序,当用户登录时,他收到了一些数据作为响应,但如果响应不是我所期望的,应用程序就会崩溃。
让我向您展示以下内容:
我创建了一个接口来告诉 Typescript 我期望的数据。
export interface AuthResponseData {
token: string;
expires: string;
role: number;
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个方法来将登录数据发送到服务器。
login(user: string, password: string){
return this.http.post<AuthResponseData>(
'https://localhost:44344/api/auth', { user: user, pwd: password }
).pipe(
catchError(this.handleError),
tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
);
}
Run Code Online (Sandbox Code Playgroud)
我期待如果来自服务器的响应与接口不匹配,那么 Angular 将重定向到catchError. 但不会发生。
现在我的问题是:有什么方法可以检查 API 响应是否等于接口,如果不是则抛出错误。或者我问的是不可能的?
更新:
搜索后,我发现接口在运行时消失了,因此无法将 api 响应与接口进行比较(据我所知)。但我一直在寻找一种以动态方式检查 api 响应的方法。我认为取决于 api 响应总是正确的,这并不是真正安全的。所以我应该检查 API 响应。我怎样才能做到这一点?
希望你能帮助我,谢谢:)
我正在使用TypeScript 中的React Google Login库。它具有 TypeScript 的类型绑定,但所有示例都是 JavaScript 语言,而且我对 TypeScript 还很陌生。
设置代码如下所示:
<GoogleLogin
clientId="client-id-value"
onSuccess={successResponseGoogle}
onFailure={failureResponseGoogle}
cookiePolicy={'single_host_origin'}
/>
Run Code Online (Sandbox Code Playgroud)
在 TypeScript 中,onSuccess 回调的签名是:
readonly onSuccess: (response: GoogleLoginResponse | GoogleLoginResponseOffline) => void
Run Code Online (Sandbox Code Playgroud)
该GoogleLoginResponseOffline类型只有一个属性 ,code其中GoogleLoginResponse具有一系列属性来访问经过身份验证的用户的详细信息。
我遇到的问题是 TypeScript 不允许我访问响应参数上的任何 GoogleLoginResponse 属性,例如
“GoogleLoginResponseOffline 类型上不存在属性‘getBasicProfile’”
我已尝试以下方法来转换或检查参数的类型,但都给出了一种或另一种类型的错误。我的函数如下所示:
const responseGoogleSuccess = (response: GoogleLoginResponse|GoogleLoginResponseOffline) => {
// Tried to check for property to identify type
if(response.googleId){ // Property 'googleId' does not exist on type 'GoogleLoginResponseOffline'
const profile = response.getBasicProfile(); // Property 'getBasicProfile' …Run Code Online (Sandbox Code Playgroud) 如果我有一个普通的JavaScript对象和一个TypeScript接口,我怎样才能编写一个断言符合我接口的对象的测试?
interface Person {
name: string
age?: number
}
describe('Person interface check', () => {
it ('should conform to "Person" interface', () => {
let obj1 = {name: "Mohsen"};
let obj2 = {name: "Hommer", age: 40};
expect(obj1) // ????
});
});
Run Code Online (Sandbox Code Playgroud)
编辑:我不想做深刻的断言,例如expect(obj1.name).to.be.a.string
typescript ×12
javascript ×4
angular ×3
angular8 ×1
class ×1
instanceof ×1
interface ×1
json ×1
models ×1
reactjs ×1
string ×1
testing ×1
typechecking ×1
typeguards ×1