简体   繁体   English

Typescript:在对象声明中指定类型

[英]Typescript: Specify type in object declaration

var a = {
    b:null, 
}

I want to specify that the type of ab is (num:number) => void while still setting it to null . 我想指定ab的类型是(num:number) => void同时仍然将其设置为null

Is it possible to do without using class or interface? 是否可以不使用类或接口?

This should work: 这应该工作:

let a = {
  b: <(number) => void> null
};

Or you can use a type declaration to make your special function explicit: 或者您可以使用类型声明来使您的特殊函数显式:

declare type MyFun = (number) => void;
let a = {
  b: <MyFun> null
};

Although it's not necessary, I tend to make use of type declarations in my code when there the function has semantics that is not easily caught in the type signature, but can be specified easily in a name. 虽然没有必要,但是当函数具有不容易在类型签名中捕获的语义时,我倾向于在我的代码中使用类型声明,但是可以在名称中轻松指定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM