TypeScript reuse object's props All In One
TypeScript reuse object's props All In One
demos
- type alias
export {};
const log = console.log;
// type CSSProps = { [prop: string]: CSSProps };
// type CSSProps = CSSProps[];
type CSSProps = number | string | { [prop: string]: CSSProps } | CSSProps[];
type CSSStyle = Record<string, CSSProps>
// type CSSStyle = {
// [x: string]: CSSProps;
// }
const cssStyleObject1: CSSProps = {
color: "#0f0",
background: "#000",
width: 100,
arr: [
"red",
"green",
"blue",
],
obj: {
"font-size": "12px",
"font-weight": 600,
},
}
const cssStyleObject2 = {
color: "#0f0",
background: "#000",
width: 100,
arr: [
"red",
"green",
"blue",
],
obj: {
"font-size": "12px",
"font-weight": 600,
},
} satisfies CSSProps;
// ✅ 正确的属性,有智能提示
log(cssStyleObject2.arr)
// (property) arr: string[]
export {};
const log = console.log;
// type CSSProps = { [prop: string]: CSSProps };
// type CSSProps = CSSProps[];
type CSSProps = number | string | { [prop: string]: CSSProps } | CSSProps[];
type CSSStyle = Record<string, CSSProps>
// type CSSStyle = {
// [x: string]: CSSProps;
// }
const cssStyleObject1: CSSProps = {
color: "#0f0",
background: "#000",
width: 100,
arr: [
"red",
"green",
"blue",
],
obj: {
"font-size": "12px",
"font-weight": 600,
},
}
const cssStyleObject2 = {
...cssStyleObject1,
} satisfies CSSProps;
// ❌ 不好使,无智能提示
log(cssStyleObject2.arr)
// CSSProps
export {};
const log = console.log;
// type alias & object
type Person = {
name: string;
salary: number;
};
// variable declaration with types
let employee: Person;
let admin: Person;
employee = {
name: "John",
salary: 10000,
};
admin = {
name: "Eric",
salary: 20000,
};
export {};
const log = console.log;
// type alias & object
type Person = {
name: string;
salary: number;
};
let employee: Person;
// typeof
let admin: typeof employee;
employee = {
name: "John",
salary: 10000,
};
admin = {
name: "Eric",
salary: 20000,
};
https://www.typescriptlang.org/docs/handbook/2/typeof-types.html
- interface
export {};
const log = console.log;
// interface
interface Person {
name: string;
salary: number;
};
let employee: Person;
// typeof
let admin: typeof employee;
employee = {
name: "John",
salary: 10000,
};
admin = {
name: "Eric",
salary: 20000,
};
https://www.typescriptlang.org/docs/handbook/interfaces.html
https://www.typescriptlang.org/docs/handbook/2/objects.html
Windows emoji 快捷键 🚀
Win
+.
/Win
+;
https://www.cnblogs.com/xgqfrms/p/14209166.html
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://www.typescriptlang.org/play
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17067470.html
未经授权禁止转载,违者必究!