Comments (7)
interface写法
定义类型
interface IAnimal {
name: string;
}
定义函数
interface IAnimal {
(name:string): void
}
定义混合类型
const createLogger = (level: 'log' | 'info' | 'warn' | 'error') => {
return function (...args: any) {
if (process.env.NODE_ENV == 'production') return
if (!console[level]) return
console[level].apply(console, args)
}
}
interface ILogFunc {
(message?: any, ...optionalParams: any[]): void
log(message?: any, ...optionalParams: any[]): void
info(message?: any, ...optionalParams: any[]): void
warn(message?: any, ...optionalParams: any[]): void
error(message?: any, ...optionalParams: any[]): void
}
/**
* 用于底层 console 打印 log
* - log('xxxx')
* - log.info('xxx')
* - log.error('xxx')
*/
export const log: ILogFunc = createLogger('log') as any
log.warn = createLogger('warn')
log.info = createLogger('info')
log.error = createLogger('error')
如果只声明函数,是不是使用type更好理解些
const fly = (name:string): string
from blogs.
as的妙用
当某些lib或者方法不具备ts声明时,可以这样实现一个类型约束
const config = require('config') as {
get: <T>(name: string) => T
}
const passportConf = config.get<PassportConf>('passport')
from blogs.
TypeScript的类型工具函数
可参考上面的ts类型库,或者自己学习下面的玩法:
from blogs.
react篇
react hooks是最流行的方式,先记录函数式组件的ts写法。
函数式组件,声明参数类型
原则
- 函数式组件类型可以使用React.FC,使用这个类型有个好处就是,提醒你必须返回一个ReactNode
在@types/react中已经预定义一个类型type SFC
,它也是类型interface StatelessComponent
的一个别名,此外,它已经有预定义的children和其他(defaultProps、displayName等等…),所以我们不用每次都自己编写!
- 推荐使用type声明Props类型,还可以处理defaultProps,个人感觉算最佳写法:
type IFunExampleProps = {
values?: string;
onChange?: (url: string) => any;
}
const FuncExample: SFC<IFunExampleProps> = ({
values = 'v1'
}) => {
return <div></div>
}
- 参数不多,可以直接写在参数后面,一个大对象
const UploadScreen = (props: {
values?: string;
onChange?: (url: string) => any;
}) => {
// do some thing
}
类型声明
type Props = {
onClick(e: MouseEvent<HTMLElement>): void;
color?: string;
};
- MouseEvent
- HTMLElement
参考
from blogs.
window,dom的类型
在ts项目里,可以直接使用WindowEventMap
,DocumentEventMap
类型。通过commad+鼠标键
进入,可发现定义在typescript>lib>lib.dom.d.ts
文件里。而这个定义文件是vscode引入的,不需要我们自己引入。
keyof的妙用
可以用于获取某种类型的所有键,其返回类型是联合类型。更多信息可阅读:http://www.semlinker.com/ts-keyof/
export type WindowEventName = keyof WindowEventMap
export type DocumentEventName = keyof DocumentEventMap
泛型和范型约束
type Partial<T> = { [P in keyof T]?: T[P] };
更多参考:https://lucifer.ren/blog/2020/06/16/ts-generics/
函数重载
函数重载让编译器根据函数的输入决定函数的输出,从而推断出更准确的类型
/**
* Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
*
* Overload 1: Omitted Window target
*
* @see {@link https://vueuse.org/useEventListener}
* @param event
* @param listener
* @param options
*/
export function useEventListener<E extends keyof WindowEventMap>(event: E, listener: (this: Window, ev: WindowEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn
/**
* Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
*
* Overload 2: Explicitly Window target
*
* @see {@link https://vueuse.org/useEventListener}
* @param target
* @param event
* @param listener
* @param options
*/
export function useEventListener<E extends keyof WindowEventMap>(target: Window, event: E, listener: (this: Window, ev: WindowEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn
/**
* Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
*
* Overload 3: Explicitly Document target
*
* @see {@link https://vueuse.org/useEventListener}
* @param target
* @param event
* @param listener
* @param options
*/
export function useEventListener<E extends keyof DocumentEventMap>(target: Document, event: E, listener: (this: Document, ev: DocumentEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn
/**
* Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
*
* Overload 4: Custom event target with event type infer
*
* @see {@link https://vueuse.org/useEventListener}
* @param target
* @param event
* @param listener
* @param options
*/
export function useEventListener<Names extends string, EventType = Event>(target: InferEventTarget<Names>, event: Names, listener: GeneralEventListener<EventType>, options?: boolean | AddEventListenerOptions): Fn
/**
* Register using addEventListener on mounted, and removeEventListener automatically on unmounted.
*
* Overload 5: Custom event target fallback
*
* @see {@link https://vueuse.org/useEventListener}
* @param target
* @param event
* @param listener
* @param options
*/
export function useEventListener<EventType = Event>(target: MaybeRef<EventTarget | null | undefined>, event: string, listener: GeneralEventListener<EventType>, options?: boolean | AddEventListenerOptions): Fn
export function useEventListener(...args: any[]) { }
更多参考:https://fullstackbb.com/typescript/function-overloads-in-typescript/
关键词
from blogs.
返回值类型推导
q:封装一个高阶工具函数,参数为function,返回值为function的返回值,可以在不主动定义泛型,获取到返回值数据的正确类型。
举例: useMemo就实现了这样的功能
const { Editor } = useMemo(
() =>
initSunmaoUIEditor({
defaultApplication: app,
defaultModules: modules,
runtimeProps: config,
storageHandler: {
onSaveApp: function (app) {
return saveApp(name, app);
},
onSaveModules: function (modules) {
return saveModules(modules);
},
},
}),
[app, modules, name]
);
useMemo如何实现类型推导的?
// todo 贴源码
from blogs.
CssType
在ts里,需要定义css相关的类型,可以使用这个npm包
import type * as CSS from 'csstype';
const style: CSS.Properties = {
colour: 'white', // Type error on property
textAlign: 'middle', // Type error on value
};
链接: https://www.npmjs.com/package/csstype
from blogs.
Related Issues (20)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blogs.