Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一些建议 #216

Open
linjialiang opened this issue Nov 20, 2021 · 3 comments
Open

一些建议 #216

linjialiang opened this issue Nov 20, 2021 · 3 comments

Comments

@linjialiang
Copy link

用接口定义函数的形状

我们也可以使用接口的方式来定义一个函数需要符合的形状:

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function (source: string, subString: string) {
    return source.search(subString) !== -1;
};
  • 建议:定义了接口的函数,是否应该省略类型定义,ts 已经可以自动推导

    interface SearchFunc {
        (source: string, subString: string): boolean;
    }
    
    let mySearch: SearchFunc;
    - mySearch = function (source: string, subString: string) {
    + mySearch = function (source, subString) {
        return source.search(subString) !== -1;
    };
@linjialiang
Copy link
Author

箭头函数可选参数

const xjjInfo: (name: string, age?: number) => void = (
  name: string,
  age: number
) => {
  if (age) {
    console.log(`小姐姐姓名:${name}, 今年:${age}岁`);
  } else {
    console.log(`小姐姐姓名:${name}`);
  }
};

下面哪种写法更加合理

const xjjInfo: (name: string, age?: number) => void = (
  ...
- age: number
+ age?: number
) => {
  ...
};

@linjialiang
Copy link
Author

下面这句话是有问题的

- 需要注意的是,可选参数必须接在必需参数后面。换句话说,可选参数后面不允许再出现必需参数了
+ 需要注意的是,函数允许参数全部都是可选参数,可选参数后面不允许再出现必需参数

@linjialiang
Copy link
Author

linjialiang commented Nov 20, 2021

下面这条断言语句会报错

(window as any).foo = 1;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant