ts中的修饰符
- public: 任何地方
- private:只能在类的内部访问
- protected:能在类的内部访问和子类访问
- readonly:属性设置为只读
const和readonly的区别
- const用于变量,readonly用于属性
- const在运行时检查,readonly在编译时检查
- 使用const变量保存的数组,可以使用push、pop等方法。使用ReadonlyArray声明的数组不能使用push、pop等方法;
ts中同名的interface或者同名的interface和class可以合并么?
type PageInfo = {
title: string
}
type Page = 'about' | 'home'
const x:Record<Page, PageInfo> = {
about: { title: 'about' },
home: { title: 'home' }
}
function mapObject<K extends number | string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U> {
const res: any = {}
for (const key in obj) {
res[key] = f(obj[key])
}
return res
}
const names = { 0: 'hello', 1: 'word', 2: 'bye' }
const lengths = mapObject(names, (s) => s.length)
console.log(lengths)
type Proxy<T> = {
get(): T,
set(value: T): void
}
type Proxify<T> = {
[P in keyof T]: Proxy<T[P]>
}
function proxify<T>(obj: T): Proxify<T> {
const result = {} as Proxify<T>
for (const key in obj) {
result[key] = {
get: () => obj[key],
set: (value) => obj[key] = value
}
}
return result
}
let props = {
name:
age: 18
}
let proxyProps = proxify(props)
console.log(proxyProps.name.get())
function unproxify<T>(obj: Proxify<T>): T {
const result = {} as T
for (const key in obj) {
result[key] = obj[key].get()
}
return result
}
let unproxifyProps = unproxify(proxyProps)
console.log(unproxifyProps)
type PartSelect<T> = {
[K in keyof T]: T[K] extends Function ? K : never
}
interface Part {
id: number;
name: string;
fn1(): void;
fn2(userName: string): void
}
type NewPart = PartSelect<Part>